HttpClient.GetAsync returns 某些网站的奇怪结果
HttpClient.GetAsync returns weird result for some websites
请考虑这个简单的代码:
private async void button3_Click(object sender, EventArgs e)
{
textBox1.Text = "It begins...";
await DoAsync_Button3();
}
private async Task DoAsync_Button3()
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("https://www.whosebug.com/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
textBox1.Text = responseBody;
}
和简单的 UI:
问题是对于某些网站,我得到了一些奇怪的结果。例如:https://www.dotnetperls.com/
我得到了这个结果:
我得到了奇怪的结果,而 StatusCode
是 200。我如何确定问题出在哪里?谢谢
您需要解压缩响应:
HttpClient httpClient = new HttpClient(new HttpClientHandler
{
AutomaticDecompression = System.Net.DecompressionMethods.All
});
string responseAsString = await httpClient.GetStringAsync("https://www.dotnetperls.com/");
Console.WriteLine(responseAsString);
如果您使用的是 .NET 5 或 6,则可以使用 SocketsHttpHandler
而不是 HttpClientHandler
。
请考虑这个简单的代码:
private async void button3_Click(object sender, EventArgs e)
{
textBox1.Text = "It begins...";
await DoAsync_Button3();
}
private async Task DoAsync_Button3()
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("https://www.whosebug.com/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
textBox1.Text = responseBody;
}
和简单的 UI:
问题是对于某些网站,我得到了一些奇怪的结果。例如:https://www.dotnetperls.com/
我得到了这个结果:
我得到了奇怪的结果,而 StatusCode
是 200。我如何确定问题出在哪里?谢谢
您需要解压缩响应:
HttpClient httpClient = new HttpClient(new HttpClientHandler
{
AutomaticDecompression = System.Net.DecompressionMethods.All
});
string responseAsString = await httpClient.GetStringAsync("https://www.dotnetperls.com/");
Console.WriteLine(responseAsString);
如果您使用的是 .NET 5 或 6,则可以使用 SocketsHttpHandler
而不是 HttpClientHandler
。