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.
Advertisement
Answer
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.