Simply I want to access internet-world from inside my web-application using the following code.
public static string BrowseURL(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "GET";
request.Credentials = CredentialCache.DefaultCredentials;
//
request.Proxy = WebProxy.GetDefaultProxy();
request.Proxy.Credentials = CredentialCache.DefaultCredentials;
//
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(response.CharacterSet));
string responseData = reader.ReadToEnd();
return responseData;
}
On my development machine it works fine, but on production server I faced a problem of "Bad Gateway" when reaching GetResponse(), I realized that it was an authentication problem, and after some google_ing, I found a good thread that speaks about solving Proxy problems with authentication. Now, the following code is working properly on my production environment.
public static string BrowseURL(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "GET";
request.Credentials = CredentialCache.DefaultCredentials;
//that is the solution
WebProxy proxy = new WebProxy("proxy ");
proxy.Credentials = new NetworkCredential("userName", "Password", "Domain");
request.Proxy = proxy;
//
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(response.CharacterSet));
string responseData = reader.ReadToEnd();
return responseData;
}