How can i get IE credentials to use in my code?

2019-04-14 06:23发布

问题:

I'm currently developing an IE plugin using SpicIE.

This plugin does some web scraping similar to the example posted on MSDN:

WebRequest request = WebRequest.Create ("http://www.contoso.com/default.html");

request.Credentials = CredentialCache.DefaultCredentials;

HttpWebResponse response = (HttpWebResponse)request.GetResponse ();

Stream dataStream = response.GetResponseStream ();

StreamReader reader = new StreamReader (dataStream);

string responseFromServer = reader.ReadToEnd ();

reader.Close ();
dataStream.Close ();
response.Close ();

However, when i run this code i receive the following error message:

The remote server returned an error: (407) Proxy Authentication Required.

I'm currently working behind a proxy server and used the NetworkCredential class to manually provide my network credentials

request.Credentials = new System.Net.NetworkCredential("name", "password", "domain");

but i still receive the same error.

Even if my problem is solved, i know that some users of the plugin will be behind a proxy server.

I want to know how i can get IE credentials and use it in my code to assign it to request.Credentials.

Maybe something like this:

request.Credentials = IE.DefaultCredentials;

回答1:

You're setting the credentials for the site, but you need credentials for the proxy.

Set request.Proxy.Credentials.

(Also, use using statements for the response/stream/reader rather than manually closing them, otherwise they'll leak when an exception is thrown.)

EDIT: For instance, to use the default credentials for the proxy as well:

request.Proxy.Credentials = CredentialCache.DefaultCredentials;