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会出现问题。

  • 相关阅读:
    Python获取会议部分的信息内容(不断完善中)
    TensorFlow学习笔记(UTF-8 问题解决 UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte)
    Tensorflow学习笔记(对MNIST经典例程的)的代码注释与理解
    virtualenvwrapper
    最小二乘法与梯度下降的区别
    Git
    Jupyter
    Linux
    Iterm2
    Homebrew
  • 原文地址:https://www.cnblogs.com/zjiacun/p/7736486.html
Copyright © 2011-2022 走看看