解压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));
    }





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值