c#httpclient 代理_C#-HttpClient和使用代理-不断得到407

在C#中使用HttpClient通过代理访问Web服务器时遇到407错误,通常是由于代理凭据设置不正确导致。正确做法是区分代理服务器的凭据和目标Web服务器的凭据。需创建WebProxy对象并设置代理凭据,然后在HttpClientHandler中配置该代理,并根据需要设置服务器认证的凭据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

httpClientHandler.Credentials是在代理已建立连接之后提供给服务器的凭据。 如果您弄错了这些,则可能会收到401或403响应。

您需要设置提供给代理的凭据,否则它将首先拒绝将您连接到服务器。 您提供给代理的凭据可能与您提供给服务器的凭据不同。 如果您弄错了这些,将得到407响应。 您得到的是407,因为您根本没有设置这些设置。

// First create a proxy object

var proxy = new WebProxy

{

Address = new Uri($"http://{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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值