【问题标题】:Retrieve Json data with HttpClient使用 HttpClient 检索 Json 数据
【发布时间】:2012-02-11 17:45:56
【问题描述】:

我正在为 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?
  • 没有Visual Studio 2011这样的东西。你的意思是Visual Studio 11 Developer Preview吗?并且没有任何版本的 Visual Studio 强制您使用 HttpClient。你到底是什么意思?您正在开发 Metro 风格的应用程序吗?
  • 我猜他正在开发 Metro 风格的应用程序,WinRT 中不再有 WebClient 类。
  • 我认为你仍然可以使用WebRequest。另外,我认为问题在于HttpClient 不会自动解压gzipped 数据。
  • 我也可以使用 WebRequest,但我发现它很复杂(我必须使用 BeginGetResponse() 女巫是异步的)。

标签: c# json microsoft-metro


【解决方案1】:

问题是响应被压缩了,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
        });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多