在Android上,我看到Http Client第一次请求需要更长的时间(大约45到65秒),然后继续,它总是小于秒 你知道为什么吗?我们怎样才能像第一次请求一样有相同的响应时间呢?
以下是示例代码
public class HttpClientTest
{
private HttpClient _httpClient;
public HttpClientTest()
{
HttpClientHandler hch = new HttpClientHandler
{
UseProxy = false,
};
_httpClient = new HttpClient(hch)
{
Timeout = new TimeSpan(0, 0, 0, 100)
};
}
public async Task TestHttpClientAsync(string key, string url)
{
DateTime startTime = DateTime.Now;
Console.WriteLine(string.Empty);
Console.WriteLine($"TestHttpClientAsync : Start : {key} : {startTime}");
var result = await _httpClient.GetByteArrayAsync(url).ConfigureAwait(false);
DateTime endTime = DateTime.Now;
Console.WriteLine(string.Empty);
Console.WriteLine($"TestHttpClientAsync : End : {key} : {endTime.Subtract(startTime).TotalMilliseconds}");
Console.WriteLine(string.Empty);
Console.WriteLine($"TestHttpClientAsync : Total : {key} : {endTime} with {result?.Length}");
Console.WriteLine(string.Empty);
}
}
以下是我如何从共享代码的MainPage的构造函数中调用它
HttpClientTest testHttpClient = new HttpClientTest();
Task.Run(() => testHttpClient.TestHttpClientAsync("Google","https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png")).Wait();
Task.Run(() => testHttpClient.TestHttpClientAsync("Microsoft","https://assets.onestore.ms/cdnfiles/external/uhf/long/9a49a7e9d8e881327e81b9eb43dabc01de70a9bb/images/microsoft-gray.png")).Wait();
Task.Run(() => testHttpClient.TestHttpClientAsync("Chrome","https://www.google.com/chrome/assets/common/images/chrome_logo_2x.png?mmfb=a5234ae3c4265f687c7fffae2760a907")).Wait();
以下是此代码的结果 参见" TestHttpClientAsync:End:"看到响应时间
TestHttpClientAsync : Start : Google : 24/01/2018 19:39:30
TestHttpClientAsync : End : Google : 4610.646
TestHttpClientAsync : Total : Google : 24/01/2018 19:39:35 with 5969
TestHttpClientAsync : Start : Microsoft : 24/01/2018 19:39:35
TestHttpClientAsync : End : Microsoft : 681.655
TestHttpClientAsync : Total : Microsoft : 24/01/2018 19:39:36 with 4054
TestHttpClientAsync : Start : Chrome : 24/01/2018 19:39:36
TestHttpClientAsync : End : Chrome : 100.584
TestHttpClientAsync : Total : Chrome : 24/01/2018 19:39:36 with 5666
答案 0 :(得分:1)
我认为问题出在DNS上,我建议您尝试将其他DNS设置为8.8.8.8并再次尝试。并且有不同的技术来解析DNS(搜索附近的服务器)并且它可能需要更多的时间,然后下一个请求,它知道什么是服务器(当解析的DNS有效时),因此请求更短。互联网上的连接还有很多因素。在我使用我的4个不同服务器的测试中,我没有看到它,虽然我使用的ModernHttpClient插件具有比基本功能更多的功能。你也可以尝试一下