以下是代码:

 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.凭据是您在代理已建立连接后向server提供的凭据.如果你弄错了,你可能会得到401或403的回复.

您需要设置为proxy提供的凭据,否则它将首先拒绝将您连接到服务器.您提供给代理的凭据可能与您提供给服务器的凭据不同.如果你弄错了,你会得到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);

.net相关问答推荐

查找 2 个已知值之间的字符串

StreamWriter.Flush() 和 StreamWriter.Close() 有什么区别?

如何从控制台应用程序中的 Task.WaitAll() 获取返回值?

value 的默认参数必须是编译时间常数?

C# 的部分类是糟糕的设计吗?

如何将浮点数向上舍入到 C# 中最近的 int?

每第 N 个字符/数字拆分一个字符串/数字?

我应该在 LINQ 查询中使用两个where子句还是&&?

在 .NET 中查找下一个 TCP 端口

如何异步 Files.ReadAllLines 并等待结果?

ObservableCollection<> 与 List<>

互锁且易变

如何修复 .NET Windows 应用程序在启动时崩溃并出现异常代码:0xE0434352?

合并两个(或更多)PDF

对构造函数进行单元测试重要吗?

如何获取当前的 ProcessID?

System.IO.IOException:使用 System.IO.Path.GetTempFileName() 时文件存在 - 解决方案?

ADO.NET Entity Framework:更新向导不会添加表

没有科学记数法的双精度字符串转换

多行 C# 插值字符串文字