The remote server returned an error: (407) Proxy A

2019-04-10 05:53发布

问题:

I referred several websites, which had answer for this question "The remote server returned an error: (407) Proxy Authentication Required." ,but none were helpful. I wrote a sample code to check the proxy authentication in office. The code throws exception.

My requirement:- Verify what the website returns. Outside office, the code works fine, but in office it throws an exception due to proxy. When I hardcode the credentials using new NetworkCredential, it works fine.

int ResponseCode;
string url = "http://www.msftncsi.com/ncsi.txt";
WebRequest request = WebRequest.Create(url);

request.Credentials = CredentialCache.DefaultCredentials;
using (WebResponse response = request.GetResponse())
 {

   Stream dataStream = response.GetResponseStream();
   StreamReader reader = new StreamReader(dataStream);
   responseFromServer = reader.ReadToEnd();
   ResponseCode = (int)((HttpWebResponse)response).StatusCode;
   reader.Close();
}

I do not want to Hardcode. I referred the solution in http://social.msdn.microsoft.com/Forums/is/csharpgeneral/thread/c06d3032-dceb-4a1a-bb6a-778fd13a938a, but even that didnt help. What am I missing?

回答1:

I had the same issue, this did the trick for me

request.Proxy.Credentials = CredentialCache.DefaultCredentials;



回答2:

There are many things here. You can try setting Credentials explicitly

request.Credentials = new NetworkCredentials(username, password)

You might need to specify proxy. By default it uses your IE proxy. You might not want that

WebRequest webRequest = WebRequest.Create("http://stackoverflow.com/");
webRequest.Proxy = new WebProxy("http://proxyserver:80/",true);