StackExchange API的JSON URL返回乱码? [英] JSON URL from StackExchange API returning jibberish?

查看:102
本文介绍了StackExchange API的JSON URL返回乱码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种感觉,我在这里做错了,但我不太确定我是否错过了一步,或者只是遇到了编码问题。这是我的代码:

I have a feeling I'm doing something wrong here, but I'm not quite sure if I'm missing a step, or am just having an encoding problem or something. Here's my code:

URL url = new URL("http://api.stackoverflow.com/0.8/questions/2886661");

   BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
   // Question q = new Gson().fromJson(in, Question.class);
   String line;
   StringBuffer content = new StringBuffer();
   while ((line = in.readLine()) != null)
   {
    content.append(line);
   }

当我打印内容时,我会得到一大堆的翅膀和特殊字符,基本上是胡言乱语。我会复制并通过它,但这不起作用。我做错了什么?

When I print content, I get a whole bunch of wingdings and special characters, basically jibberish. I would copy and past it here, but that isn't working. What am I doing wrong?

推荐答案

在这种情况下,它不是字符编码问题,而是内容编码问题;你期待文本,但服务器正在使用压缩来节省带宽。如果您在获取该网址时查看标题,则可以看到您要连接的服务器正在返回gzip压缩内容:

In this case it's not a character encoding problem, it's a content encoding problem; you're expecting text, but the server is using compression to save bandwidth. If you look at the headers when you grab that url, you can see the server you are connecting to is returning gzipped content:

GET /0.8/questions/2886661 HTTP/1.1
Host: api.stackoverflow.com

HTTP/1.1 200 OK
Server: nginx
Date: Sat, 22 May 2010 15:51:34 GMT
Content-Type: application/json; charset=utf-8
<more headers>
Content-Encoding: gzip
<more headers>

所以你需要使用像Apache的HttpClient这样的智能客户端,就像stevedbrown建议的那样(尽管你需要调整以使其自动说出Gzip ),或明确解压缩您在示例代码中获得的流。请尝试使用此代替您声明输入的行:

So you either need to use a smarter client like Apache's HttpClient as stevedbrown suggests (although you need a tweak to get it to speak Gzip automatically), or explicitly decompress the stream you got in your example code. Try this instead for the line where you declare your input:

 BufferedReader in = new BufferedReader(new InputStreamReader(new GZIPInputStream(url.openStream())));

我已经确认这适用于你想要获取的网址。

I've verified that this works for the url you are trying to grab.

这篇关于StackExchange API的JSON URL返回乱码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆