how to decode the Stack Exchange API response

﹥>﹥吖頭↗ 提交于 2021-02-08 03:48:53

问题


I am trying to retrieve the response of stack exchange api like [http://api.stackexchange.com/2.2/tags?order=desc&sort=popular&site=stackoverflow]

I am using the following code to retrieve the response

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

But I am getting the response in decoded form as ���n� �߅\f]as��DՊ�I��/�m�(��*Ʃ���Kc���

I found the similar question [https://stackoverflow.com/questions/20808901/problems-with-decoding-stack-exchange-api-response] , but I didn't find any answers for the question.

How to decode the api response?

Thanks in advance.


回答1:


The content is compressed. You need to send it through an unzip stream, like

import java.util.zip.GZIPInputStream;

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

You should also check the content encoding first, and only wrap the stream into a GZIPInputStream if the encoding actually is gzip - some proxies transparently already uncompress the stream.

See SOQuery.java for a complete sample, even though this is using java.net.HttpURLConnection rather than the apache client.



来源:https://stackoverflow.com/questions/23560740/how-to-decode-the-stack-exchange-api-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!