如何解码堆栈交换API响应



我试图检索堆栈交换api的响应,如[http://api.stackexchange.com/2.2/tags?order=desc& sort = popular&网站= 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߅]��DՊ�我��/m����*Ʃ���Kc���

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

如何解码api响应?

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

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

你也应该先检查内容编码,只有当编码实际上 gzip时,才把流包装成GZIPInputStream——一些代理已经透明地解压缩了流。

请参阅SOQuery.java获得完整的示例,尽管这是使用java.net.HttpURLConnection而不是apache客户机。

相关内容

  • 没有找到相关文章

最新更新