HttpURLConnection get请求解压gzip格式的数据

原文链接:https://blog.csdn.net/lianzhang861/article/details/80840242

代码在原文的基础上增加了Transfer-Encoding的判断。

最近项目在使用 http://wthrcdn.etouch.cn/weather_mini
获取天气预报数据,但此接口只能用get方法请求,而且返回数据一直是乱码,原来返回数据用gzip格式压缩了,所以我的方

法中增加了判断是否为gzip并解压

public static String sendGet(String url) {
    StringBuffer stringBuffer = new StringBuffer();
    try {
        URL realUrl = new URL(url);

        HttpURLConnection httpURLConnection = (HttpURLConnection) realUrl.openConnection();
        //在这里设置一些属性,详细见UrlConnection文档,HttpURLConnection是UrlConnection的子类
        //设置连接超时为5秒
        httpURLConnection.setConnectTimeout(5000);
        //设定请求方式(默认为get)
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.setRequestProperty("accept", "*/*");
        httpURLConnection.setRequestProperty("Accept-Charset", "UTF-8");
        httpURLConnection.setRequestProperty("contentType", "UTF-8");
        httpURLConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
        //建立到远程对象的实际连接
        httpURLConnection.connect();
        GZIPInputStream gZIPInputStream = null;
        String encoding = httpURLConnection.getContentEncoding();
        String TransferEncoding = httpURLConnection.getHeaderField("Transfer-Encoding");

        if((null!=encoding && encoding.equals("gzip")) || (null!=TransferEncoding && TransferEncoding.equals("chunked"))){
            gZIPInputStream = new GZIPInputStream(httpURLConnection.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gZIPInputStream));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                //转化为UTF-8的编码格式
                line = new String(line.getBytes("UTF-8"));
                stringBuffer.append(line);
            }
            bufferedReader.close();
        }else{
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                //转化为UTF-8的编码格式
                line = new String(line.getBytes("UTF-8"));
                stringBuffer.append(line);
            }
            bufferedReader.close();
        }
        //返回打开连接读取的输入流,输入流转化为StringBuffer类型,这一套流程要记住,常用


        httpURLConnection.disconnect();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return stringBuffer.toString();
}
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值