14

我使用以下代码从互联网上获取 html 数据:

WebProxy p = new WebProxy("localproxyIP:8080", true);
p.Credentials = new NetworkCredential("domain\\user", "password");
WebRequest.DefaultWebProxy = p;
WebClient client = new WebClient();
string downloadString = client.DownloadString("http://www.google.com");

但出现以下错误:“需要代理身份验证”。我不能使用默认代理,因为我的代码在没有默认代理设置的特殊帐户下从 Windows 服务运行。所以,我想在我的代码中指定所有代理设置。请告诉我如何解决这个错误。

4

3 回答 3

50

这对我有用:

IWebProxy defaultWebProxy = WebRequest.DefaultWebProxy;
defaultWebProxy.Credentials = CredentialCache.DefaultCredentials;
client = new WebClient
    {
        Proxy = defaultWebProxy
    };
string downloadString = client.DownloadString(...);
于 2013-06-19T09:02:16.480 回答
21

您必须设置 WebClient.Proxy 属性..

WebProxy p = new WebProxy("localproxyIP:8080", true);
p.Credentials = new NetworkCredential("domain\\user", "password");
WebRequest.DefaultWebProxy = p;
WebClient client = new WebClient();
**client.Proxy = p;**
string downloadString = client.DownloadString("http://www.google.com");
于 2012-10-22T10:08:28.717 回答
1

试试这个代码

var transferProxy = new WebProxy("localproxyIP:8080", true);
transferProxy.Credentials = new NetworkCredential("user", "password", "domain");
var transferRequest = WebRequest.Create("http://www.google.com");
transferRequest.Proxy = transferProxy;
HttpWebResponse transferResponse = 
    (HttpWebResponse)transferRequest.GetResponse(); 
System.IO.Stream outputStream = transferResponse.GetResponseStream();
于 2012-10-22T10:05:35.850 回答