如何解码Stack Exchange API响应

时间:2014-05-09 09:11:06

标签: java json stackexchange-api

我正在尝试检索堆栈交换api的响应 [http://api.stackexchange.com/2.2/tags?order=desc&sort=popular&site=stackoverflow]

我使用以下代码来检索响应

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;


public class RetrieveAllTag {

    public static void main(String... args) {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet("http://api.stackexchange.com/2.2/tags?order=desc&sort=popular&site=stackoverflow");
        HttpResponse response = null;

        try {
            response = httpClient.execute(httpGet);
            InputStream content = response.getEntity().getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(content,"UTF-8"));
            StringBuilder stringBuilder = new StringBuilder();
            String inputLine;
            while ((inputLine = reader.readLine()) != null) {
                stringBuilder.append(inputLine);
                stringBuilder.append("\n");
            }
            System.out.println(stringBuilder.toString());

        }
        catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        finally {
            httpClient.getConnectionManager().shutdown();
        }
    }
}

但我以解码的形式获得响应 n ߅\ f]as DՊ I / m ( *Σ Kc

我发现了类似的问题[https://stackoverflow.com/questions/20808901/problems-with-decoding-stack-exchange-api-response], 但我没有找到任何问题的答案。

如何解码api响应?

提前致谢。

1 个答案:

答案 0 :(得分:2)

内容已压缩。您需要通过解压缩流发送它,例如

import java.util.zip.GZIPInputStream;

...
InputStream content = response.getEntity().getContent();
content = new GZIPInputStream(content);
...

您还应该首先检查内容编码,如果编码实际上 GZIPInputStream,则只将流包装到gzip中 - 某些代理透明地已经解压缩了流。

有关完整示例,请参阅SOQuery.java,即使这是使用java.net.HttpURLConnection而不是apache客户端。