我正在为 Visual Studio 2011 编程,所以我不得不使用 HttpClient
。我需要从网络上检索一些 JSON 数据,但我想我需要将内容设置为“json 数据”或其他内容,因为仅使用此代码时我总是会收到奇怪的字符:
HttpClient client = new HttpClient();
var response = client.Get("http://api.stackoverflow.com/1.1/users");
var content = response.Content.ReadAsString();
那么我该如何设置内容或者我应该怎么做才能得到正确的数据呢?
编辑:
输出:像这样的东西:������
最佳答案
问题是响应是压缩的,HttpClient
默认不会自动解压缩。
使用 WebClient
,您可以 create a derived class and set the AutomaticDecompression
of the underlying HttpWebRequest
.
您不能使用 HttpClient
来做到这一点,因为它没有任何合适的 virtual
方法。但是你可以通过传递 HttpClientHandler
来做到这一点到它的构造函数:
var client =
new HttpClient(
new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.GZip
| DecompressionMethods.Deflate
});
关于c# - 使用 HttpClient 检索 Json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9242472/