我正在寻找便携式替代Mono HttpClient堆栈。便携式Mono版本[常规Mono堆栈的一部分]有bug。我一直在尝试修复影响我们项目的一个特定错误。由于异步操作所需的库的高度异步性,Mono代码中缺少文档和注释,因此需要很长时间。 我看到微软并不打算在C#中实现Http堆栈,而是使用可靠的库 - WinHttp和libcurl。不幸的是,将libcurl移植到Mono也是一项工作。 从法律上讲,HttpClient允许替换处理程序,创建一个替代堆栈。适用于iOS和适用于iOS / Android和其他平台的ModernHttpClient的CFNetwork处理程序。然而,对于我来说,ModernHttpClient对我来说也不起作用。 有什么建议?我的代码如下:
class Program
{
static void Main(string[] args)
{
var threadCancelationToken = new CancellationTokenSource();
var sl = new StatusLoop();
sl.HttpClientTimeout = int.Parse(args[0]);
sl.StatusFreq = int.Parse(args[1]);
Task.Run(async () => await sl.RunStatusLoop(threadCancelationToken.Token), threadCancelationToken.Token);
Console.ReadKey();
}
}
public class StatusLoop
{
public int HttpClientTimeout;
public int StatusFreq;
public async Task RunStatusLoop(CancellationToken cancellationToken)
{
// var handler = new HttpClientHandler
var handler = new NativeMessageHandler
{
Credentials = new NetworkCredential("username", "password"),
PreAuthenticate = true,
UseProxy = false
};
// var httpClient = new HttpClient(new NativeMessageHandler())
var httpClient = new HttpClient(handler)
{
Timeout = TimeSpan.FromSeconds(this.HttpClientTimeout)
};
httpClient.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
httpClient.DefaultRequestHeaders.ExpectContinue = false;
ServicePointManager.ServerCertificateValidationCallback +=
(sender, certificate, chain, sslPolicyErrors) => true;
while (true)
{
try
{
var httpResponse = await httpClient.GetAsync("https://192.168.1.22/api/v1/system/status/", cancellationToken);
if (httpResponse.IsSuccessStatusCode)
Console.Write(".");
}
catch (Exception ex)
{
Console.WriteLine ("HttpClientGetStatus - exception\n\r" + ex.ToString());
}
Thread.Sleep(this.StatusFreq * 1000);
}
}
}
如果您在Linux / Mac上使用过替代的HttpClientHandler,请分享您的经验。
谢谢