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

达里尔

您将代理凭据设置在错误的位置。

httpClientHandler.Credentials是在代理已建立连接之后提供给服务器的凭据如果您弄错了这些,则可能会收到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);

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

Related 相关文章

热门标签

归档