C# WebProxy 错误:需要代理身份验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13008964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:19:52  来源:igfitidea点击:

WebProxy error: Proxy Authentication Required

c#.netwebclientnetworkcredentialswebproxy

提问by Oleg Ignatov

I use the following code to obtaing html data from the internet:

我使用以下代码从互联网上获取 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");

But the following error is appeared: "Proxy Authentication Required". I can't use default proxy because of my code runs from windows service under the special account which there is no default proxy settings for. So, I want to specidy all proxy settings in my code. Please advice me how to resolve this error.

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

采纳答案by 2GDev

You've to set the WebClient.Proxy Property..

您必须设置 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");

回答by Marco

Try this code

试试这个代码

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();

回答by Johan Larsson

This worked for me:

这对我有用:

IWebProxy defaultWebProxy = WebRequest.DefaultWebProxy;
defaultWebProxy.Credentials = CredentialCache.DefaultCredentials;
client = new WebClient
    {
        Proxy = defaultWebProxy
    };
string downloadString = client.DownloadString(...);