【问题标题】:how to decode the Stack Exchange API response如何解码 Stack Exchange API 响应
【发布时间】:2014-05-09 09:11:06
【问题描述】:

我正在尝试检索堆栈交换 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();
        }
    }
}

但我得到的是解码形式的响应 ����������\f]as��DՊ�I��/�m�(��*Ʃ���Kc���

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

如何解码 api 响应?

提前致谢。

【问题讨论】:

    标签: java json stackexchange-api


    【解决方案1】:

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

    import java.util.zip.GZIPInputStream;
    
    ...
    InputStream content = response.getEntity().getContent();
    content = new GZIPInputStream(content);
    ...
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-21
      • 1970-01-01
      • 2018-10-21
      • 2020-10-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多