2010-05-22 47 views
4

我有一種感覺,我在這裏做錯了事,但我不太確定我是否錯過了一個步驟,或者只是遇到了編碼問題或其他問題。這裏是我的代碼:StackExchange API返回Jibberish的JSON URL?

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); 
    } 

當我打印的內容,我得到了一大堆宋體和特殊字符,基本上jibberish的。我會複製並在這裏過去,但那不起作用。我究竟做錯了什麼?

回答

5

在這種情況下,它不是一個字符編碼問題,它是一個內容編碼問題;您正在等待文本,但服務器正在使用壓縮來節省帶寬。如果你看一下頭時,你抓住這個URL,你可以看到你正在連接的服務器返回gzip壓縮的內容:

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提出一個更聰明的客戶端(雖然你需要a tweak to get it to speak Gzip automatically),或者明確地解壓你在示例代碼中獲得的流。試試這個,而不是你聲明你的輸入的行:

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

我已驗證,這適用於你想要抓取的網址。

1

改爲使用Apache Http Client,它會正確處理字符轉換。從that site's examples

public final static void main(String[] args) throws Exception { 

    HttpClient httpclient = new DefaultHttpClient(); 

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

    System.out.println("executing request " + httpget.getURI()); 

    // Create a response handler 
    ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
    String responseBody = httpclient.execute(httpget, responseHandler); 
    System.out.println(responseBody); 

    System.out.println("----------------------------------------"); 

    // When HttpClient instance is no longer needed, 
    // shut down the connection manager to ensure 
    // immediate deallocation of all system resources 
    httpclient.getConnectionManager().shutdown();   
} 

在這種情況下,看到http://svn.apache.org/repos/asf/httpcomponents/httpclient/branches/4.0.x/httpclient/src/examples/org/apache/http/examples/client/ClientGZipContentCompression.java,它展示瞭如何處理用gzip內容。

+0

這不處理解壓api.stackoverflow.com返回的內容的問題。 – Bkkbrad 2010-05-22 17:21:06

1

有時API調用響應被壓縮,例如。 StackExchange API。請仔細閱讀他們的文檔並檢查他們正在使用的壓縮。有些使用GZIP或DEFLATE壓縮。在GZIP壓縮的情況下使用以下內容。

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