Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

java - JSON URL from StackExchange API returning jibberish?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...