HttpClient 和使用代理-不断得到407

密码如下:

 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类,同样的代理设置可以正常工作

141768 次浏览

你把代理凭证设置错了地方。

HttpClientHandler.凭据是在代理已经建立连接之后提供给 服务器的凭据。如果你弄错了,你可能会得到401或403的回复。

您需要设置给予 代理人的凭据,否则它将首先拒绝将您连接到服务器。提供给代理的凭据可能与提供给服务器的凭据不同。如果你弄错了,你会得到407回复。你得到了407,因为你从来没有设置这些。

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

我找到了一些关于这个 来自 social.msdn.microsoft.com的有用信息。通过回复、测试以及对 WebProxy 类的研究,您需要将代理凭据传递给代理对象,而不是 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。

你需要通过一个代理处理程序。尝试这个它为我工作

var handler = new HttpClientHandler();
handler.DefaultProxyCredentials = CredentialCache.DefaultCredentials;


var client = new HttpClient(handler);


HttpResponseMessage response = await client.SendAsync();