问题
This is my code:
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(strJson, "UTF-8"));
httpPost.setHeader("api_key", "<TSssssssssssssaaa7>");
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept-Encoding", "gzip");
response = httpClient.execute(httpPost);
resp=EntityUtils.toString(response.getEntity(), "UTF-8");
Log.w("QueingSystem", strJson);
Log.w("QueingSystem", EntityUtils.toString(response.getEntity(), "UTF-8"));
Log.w("QueingSystem", EntityUtils.toString(response.getEntity()));
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
And my output in the log is as follows:
��������������V*J-.��+NU��VJ�O�&�:J���ʼn�@��ciIFj^IfrbIf~��[bfNj�Rm-���n��;������
Can any one please help me to get the exact output of json response in String format?
回答1:
You have to manually check whether the response is gzip compressed. If it is you can wrap the response entity into a GzipDecompressingEntity to handle the decompression:
// setup request
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(strJson, "UTF-8"));
httpPost.setHeader("api_key", "<TSssssssssssssaaa7>");
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept-Encoding", "gzip");
// execute request
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
// handle gzip compression
Header contentEncodingHeader = entity.getContentEncoding();
if (contentEncodingHeader != null) {
HeaderElement[] encodings = contentEncodingHeader.getElements();
for (HeaderElement encoding : encodings) {
if (encoding.getName().equalsIgnoreCase("gzip")) {
entity = new GzipDecompressingEntity(entity);
break;
}
}
}
// get response content
resp = EntityUtils.toString(entity, "UTF-8");
来源:https://stackoverflow.com/questions/42586541/decompress-gzip-json-response-to-string-in-android