以下是代码:
HttpClient client = null;
HttpClientHandler httpClientHandler = new HttpClientHandler()
{
Proxy = new WebProxy(string.Format("{0}:{1}", proxyServerSettings.Address,
proxyServerSettings.Port),false),
PreAuthenticate = true,
UseDefaultCredentials = false,
};
this.httpClientHandler.Credentials = new NetworkCredential(proxyServerSettings.UserName,
proxyServerSettings.Password);
this.client = new HttpClient(this.httpClientHandler);
当我最终这样做时:
HttpResponseMessage httpResponseMessage = this.client.PostAsync(urlToPost, new StringContent(data, Encoding.UTF8, this.mediaType)).Result;
总是抛出
远程服务器返回错误:(407)代理验证 必需的。
我不了解我的世界。
在IE10中配置相同的代理设置或者如果我使用HttpWebRequest
类而不是
答案 0 :(得分:76)
您在错误的位置设置代理凭据。
httpClientHandler.Credentials是代理已建立连接后您提供给服务器的凭据。如果你弄错了,你可能会收到401或403的回复。
您需要设置提供给代理的凭据,否则它将首先拒绝将您连接到服务器。您提供给代理的凭据可能与您提供给服务器的凭据不同。如果你弄错了,你会得到407回复。你得到的是407,因为你根本没有设置这些。
// First create a proxy object
var proxy = new WebProxy()
{
Address = new Uri($"{proxyHost}:{proxyPort}"),
BypassOnLocal = false,
UseDefaultCredentials = false,
// *** These creds are given to the proxy server, not the web server ***
Credentials = new NetworkCredential(
userName: proxyUserName,
password: proxyPassword);
};
// Now create a client handler which uses that proxy
var httpClientHandler = new HttpClientHandler()
{
Proxy = proxy,
};
// Omit this part if you don't need to authenticate with the web server:
if (needServerAuthentication)
{
httpClientHandler.PreAuthenticate = true;
httpClientHandler.UseDefaultCredentials = false;
// *** These creds are given to the web server, not the proxy server ***
httpClientHandler.Credentials = new NetworkCredential(
userName: serverUserName,
password: serverPassword);
}
// Finally, create the HTTP client object
var client = new HttpClient(handler: httpClientHandler, disposeHandler: true);
答案 1 :(得分:2)
您需要传递代理处理程序。试试这个对我有用的
var handler = new HttpClientHandler();
handler.DefaultProxyCredentials = CredentialCache.DefaultCredentials;
var client = new HttpClient(handler);
HttpResponseMessage response = await client.SendAsync();
答案 2 :(得分:1)
我找到了一些有关此here from social.msdn.microsoft.com的有用信息。从回复,我做的测试和研究System.Net.WebProxy Class您需要将代理凭证传递到代理对象,而不是HttpClientHandler。
{
Proxy = new WebProxy(string.Format("{0}:{1}", proxyServerSettings.Address,
proxyServerSettings.Port),false),
PreAuthenticate = true,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential(proxyServerSettings.UserName,
proxyServerSettings.Password),
};
这实际上是为了验证与代理的连接,而不是HttpClientHandler。