问题描述
代码如下:
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);
当我最终做到这一点时:
And when I finally do this:
HttpResponseMessage httpResponseMessage = this.client.PostAsync(urlToPost, new StringContent(data, Encoding.UTF8, this.mediaType)).Result;
它总是抛出
远程服务器返回错误:(407) Proxy Authentication必填.
对于我的世界,我不明白这一点.
Which I do not understand for the world of me.
相同的代理设置在 IE10 中配置时工作正常,或者如果我使用 HttpWebRequest
类代替
The same proxy set up works just fine when is configured in IE10 or if I use the HttpWebRequest
class instead
推荐答案
您在错误的位置设置了代理凭据.
You're setting the proxy credentials in the wrong place.
httpClientHandler.Credentials 是您在代理建立连接后提供给 服务器 的凭据.如果您做错了这些,您可能会收到 401 或 403 响应.
httpClientHandler.Credentials are the credentials you give to the server after the proxy has already established a connection. If you get these wrong, you'll probably get a 401 or 403 response.
您需要设置提供给 代理 的凭据,否则它首先会拒绝您连接到服务器.您提供给代理的凭据可能与您提供给服务器的凭据不同.如果您弄错了这些,您将收到 407 响应.您收到 407 是因为您根本没有设置这些.
You need to set the credentials given to the proxy, or it will refuse to connect you to the server in the first place. The credentials you provide to the proxy may be different from the ones you provide to the server. If you get these wrong, you'll get a 407 response. You're getting a 407 because you never set these at all.
// First create a proxy object
var proxy = new WebProxy
{
Address = new Uri($"http://{proxyHost}:{proxyPort}"),
BypassProxyOnLocal = 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);
这篇关于HttpClient 和使用代理 - 不断得到 407的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!