zoukankan      html  css  js  c++  java
  • HttpURLConnection 接收网络数据出现乱码问题

    由于接收的数据经过gZip处理过,所以在接受的时候也要处理,并且加上编码格式(没有会出现部分数据乱码):

    具体代码实现如下:

    URL ul = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) ul.openConnection();
    conn.connect();
    InputStream in = conn.getInputStream();
    
    StringBuffer sb = new StringBuffer();
    String readLine = new String();
    GZIPInputStream gZipS=new GZIPInputStream(in);
    InputStreamReader res = new InputStreamReader(gZipS,"UTF-8");
    BufferedReader responseReader = new BufferedReader(res);
    while ((readLine = responseReader.readLine()) != null) {
    	sb.append(readLine);
    }
    responseReader.close();
    

     测试问题解决。。

    有一点需要补充的是:在使用gZip解压数据的时候,记得关闭gZip:

    String result = "";
    		GZIPInputStream gZipS = null;
    		try {
    			logger.debug("start getWeiboContent==url="+url);
    			StringBuffer sb = new StringBuffer();
    			String readLine = new String();
    			URL ul = new URL(url);
    			HttpURLConnection conn = (HttpURLConnection) ul.openConnection();
    			conn.connect();
    			in = conn.getInputStream();
    			//解析八友数据
    			gZipS=new GZIPInputStream(in);
    			InputStreamReader res = new InputStreamReader(gZipS,"UTF-8");
    			BufferedReader responseReader = new BufferedReader(res);
    			while ((readLine = responseReader.readLine()) != null) {
    				sb.append(readLine);
    			}
    			result = sb.toString();
    			responseReader.close();
    			res.close();
    			gZipS.close();
    			in.close();
    			conn.disconnect();
    			logger.debug("end getWeiboContent==url="+url);
    			
    
    		} catch (Exception e) {
    			e.printStackTrace();
    		}finally{
                if(gZipS!=null)
                {
                    try {
                    	gZipS.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    

     gZipS.close();尤其重要,而且在一个流没有关闭的时候再次操作新的gZip会出现问题。

  • 相关阅读:
    一个程序员的负罪感
    【软件安装记录篇】本地虚拟机Centos7快速安装MySQL
    三分钟熟悉进制转换与位运算
    Base64 编码原理
    Java 注解
    数据结构之链表-动图演示
    数据结构之红黑树-动图演示(下)
    数据结构之红黑树-动图演示(上)
    通过TreeMap 和 冒泡算法对JSON 进行排序
    Quartz 之 windowService
  • 原文地址:https://www.cnblogs.com/zjiacun/p/7736486.html
Copyright © 2011-2022 走看看