2

我正在尝试检索堆栈交换 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���</p>

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

如何解码 api 响应?

提前致谢。

4

1 回答 1

2

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

import java.util.zip.GZIPInputStream;

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

GZIPInputStream您还应该首先检查内容编码,并且仅在编码实际 时才将流包装到 a gzip- 一些代理已经透明地解压缩了流。

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

于 2014-05-09T09:23:32.443 回答