解压GZIP加密后的Response

         今儿同事调接口时,发现对方返回的HttpResponse是经GZIP加密的,调用一个现成的解压Util总是失败。经查阅资料,个人封装了一个自带解压功能的post方法,适用于返回结果经GZIP加密的post请求,Get请求请自行更改。废话少说,上代码。

private String postGZIP(String url, String requestJson, String authorization)throws Exception {
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httppost =null;
        String postUrl =null;
        HttpResponse response =null;
        String json =null;
        try{
            postUrl = url +"?param="+ requestJson;
            httppost =new HttpPost(postUrl);
            List<NameValuePair> params =new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("param", requestJson));
            // httppost.setEntity(new UrlEncodedFormEntity(params));
            httppost.addHeader("Content-Type","text/plain;charset=utf-8");
            // httppost.addHeader("Accept-Encoding", "gzip");
            if(null!= authorization){
                httppost.addHeader("Authorization", authorization);
            }
            response = httpClient.execute(httppost);
            InputStream is = response.getEntity().getContent();
            is =new GZIPInputStream(is);
            BufferedReader br =new BufferedReader(new InputStreamReader(is));
            String line =null;
            StringBuffer sb =new StringBuffer();
            while((line = br.readLine())!=null){
                sb.append(line);
            }
            json = sb.toString();
        }catch(Exception e){
            throw e;
        }finally{
            if(null!= httppost){
                httppost.releaseConnection();
            }
        }
        if(json ==null){
            thrownew Exception("接口无结果返回");
        }
        return json;
    }

测试方法:

@Test
    public void testGZIP()throws Exception {
        String url ="http://api.pkfare.com/test_api/shopping";
        String req ="JTdCJTIyYXV0aGVudGljYXRpb24lMjIlM0ElN0IlMjJwYXJ0bmVySWQlMjIlM0ElMjJSa3NWU1g3UGZabTF5RjA0YWRCV1lzQ0Q3TTQlM0QlMjIlMkMlMjJzaWduJTIyJTNBJTIyMTdlNzA3YjVkOWRhZTg0NTkwNjVkYmIxMzllNWYxYmQlMjIlN0QlMkMlMjJzZWFyY2glMjIlM0ElN0IlMjJhZHVsdHMlMjIlM0ExJTJDJTIyYWlybGluZSUyMiUzQSUyMkNBJTIyJTJDJTIyY2hpbGRyZW4lMjIlM0EwJTJDJTIyaW5mYW50cyUyMiUzQTAlMkMlMjJub25zdG9wJTIyJTNBMSUyQyUyMnNlYXJjaEFpckxlZ3MlMjIlM0ElNUIlN0IlMjJjYWJpbkNsYXNzJTIyJTNBJTIyRWNvbm9teSUyMiUyQyUyMmRlcGFydHVyZURhdGUlMjIlM0ElMjIyMDE2LTAzLTE2JTIyJTJDJTIyZGVzdGluYXRpb24lMjIlM0ElMjJIS0clMjIlMkMlMjJvcmlnaW4lMjIlM0ElMjJCS0slMjIlN0QlNUQlMkMlMjJzb2x1dGlvbnMlMjIlM0EyMCU3RCU3RA==";
        System.out.println(pkfareBusiness.postGZIP(url, req, null));
    }





你可能感兴趣的:(GZIP解压Response)