c# - 使用 HttpClient 检索 Json 数据

标签 c# json microsoft-metro

我正在为 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/

相关文章:

c# - 进一步削减uuid以制作短字符串

c# - 使 Windows Forms 窗体可调整大小的最佳方法

javascript - 无法访问Json数据并在canvas d3js上绘制线条

c# - 创建 Windows 应用商店应用程序时出现问题。 (Windows 8)

c# - Metro - 编写异步 c# 操作并从 javascript 调用

windows-8 - 从 Metro 应用程序检测桌面可用性(检测 ARM、检测 Windows RT 系统)

c# - 我怎样才能在 'user account control settings' 中更改从不通知?

c# - C# 中的 Monitor.Pulse 似乎不理想 : must be in lock scope

java - Google GSON 不解析从 C# 网站中的 WebMethod 检索到的 Java 中的 JSON

html - 如何从 iOS 中的文件中解析 JSON?