【发布时间】:2019-10-14 11:00:26
【问题描述】:
我正在通过下面描述的方法使用 HttpClient 发送 cURL 请求。
这个方法使用的参数是:
SelectedProxy = 存储代理参数的自定义类
Parameters.WcTimeout = 超时时间
url, header, content = cURL请求(基于此工具转换为C#https://curl.olsh.me/)。
const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
ServicePointManager.SecurityProtocol = Tls12;
string source = "";
using (var handler = new HttpClientHandler())
{
handler.UseCookies = usecookies;
WebProxy wp = new WebProxy(SelectedProxy.Address);
handler.Proxy = wp;
using (var httpClient = new HttpClient(handler))
{
httpClient.Timeout = Parameters.WcTimeout;
using (var request = new HttpRequestMessage(new HttpMethod(HttpMethod), url))
{
if (headers != null)
{
foreach (var h in headers)
{
request.Headers.TryAddWithoutValidation(h.Item1, h.Item2);
}
}
if (content != "")
{
request.Content = new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded");
}
HttpResponseMessage response = new HttpResponseMessage();
try
{
response = await httpClient.SendAsync(request);
}
catch (Exception e)
{
//Here the exception happens
}
source = await response.Content.ReadAsStringAsync();
}
}
}
return source;
如果我在没有代理的情况下运行它,它就像一个魅力。 当我使用我首先从 Chrome 测试的代理发送请求时,我的 try {} catch {} 出现以下错误。这是错误树
{"An error occurred while sending the request."}
InnerException {"Unable to connect to the remote server"}
InnerException {"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond [ProxyAdress]"}
SocketErrorCode: TimedOut
通过使用秒表,我看到 TimedOut 发生在大约 30 秒后。
我根据以下链接Whats the difference between HttpClient.Timeout and using the WebRequestHandler timeout properties?、HttpClient Timeout confusion 或 WinHttpHandler 尝试了几个不同的处理程序。
值得注意的是,WinHttpHandler 允许使用不同的错误代码,即 Error 12002 calling WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, 'The operation timed out'。根本原因是相同的,尽管它有助于定位它的错误位置(即 WinInet),这也证实了 @DavidWright 关于 HttpClient 的超时管理请求发送的不同部分的说法。
因此,我的问题来自与服务器建立连接所需的时间,这会触发 WinInet 的 30 秒超时。
我的问题是如何更改这些超时?
附带说明,值得注意的是,使用 WinInet 的 Chrome 似乎并没有受到这种超时的影响,我的应用程序的很大一部分所基于的 Cefsharp 也没有受到影响,并且相同的代理可以通过它正确发送请求.
【问题讨论】:
标签: c# curl timeout dotnet-httpclient