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

  • 相关阅读:
    sqlserver编程基本语法
    每日一记--技术小细节
    每日一记--jsp
    每日一记--session/servletContext
    每日一记--cookie
    每日一记--HashTable/HashMap/ConcurrentHashMap
    每日一记--Ajax(下)
    每日一记--Axjx
    每日一记--索引/过滤器
    每日一记--酱油日
  • 原文地址:https://www.cnblogs.com/zjiacun/p/7736486.html
Copyright © 2011-2022 走看看