2017-03-03 70 views
0

字符串這是我的代碼:解壓gzip JSON響應的Android

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

而且我在日誌中輸出如下:

��������������V*J-.��+NU��VJ�O�&�:J���ʼn�@��ciIFj^IfrbIf~��[bfNj�Rm-���n��;������ 

任何一個可以幫我得到確切的以字符串格式輸出json響應?

回答

0

您必須手動檢查響應是否爲gzip壓縮。如果它是你可以用響應實體爲GzipDecompressingEntity處理減壓:

// 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"); 
+0

實體=新GzipDecompressingEntity(實體);我得到一個錯誤無法解決 –