天天看點

JAVA Httpclient 調接口 gzip格式傳回值亂碼

當調接口傳回的值是壓縮過的,如果不做處理就會得到一長串亂碼。

//此處是将請求體封裝成為了StringEntity,若亂碼則指定utf-8
            StringEntity se = new StringEntity(jsonstr,"utf-8");
            //  StringEntity se = new StringEntity(jsonstr);
            se.setContentType("text/json");
            se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
            httpPost.setEntity(se);
            HttpResponse response = httpClient.execute(httpPost);
            Header[] headers = response.getHeaders("Content-Encoding");
            boolean isGzip = false;
            for(Header h:headers){
                if(h.getValue().equals("gzip")){
                    //傳回頭中含有gzip
                    isGzip = true;
                }
            }

            if(isGzip){
                //需要進行gzip解壓處理
                result = EntityUtils.toString(new GzipDecompressingEntity(response.getEntity()));
            }else{
                result = EntityUtils.toString(response.getEntity());
            }