首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

关于java字符集编码有关问题 URLConnection

2012-09-22 
关于java字符集编码问题 URLConnection今天遇到一字符集问题,用URLConnection来开启http访问获取数据的问

关于java字符集编码问题 URLConnection

今天遇到一字符集问题,用URLConnection来开启http访问获取数据的问题,对方是utf-8编码,到了自己这边,成了乱码。

<%@ page contentType="text/html; charset=GBK"%>

这是jsp头。

public String getDocumentAt(String urlString) {StringBuffer document = new StringBuffer();try {URL url = new URL(urlString);URLConnection conn = url.openConnection();BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));String line = null;while ((line = reader.readLine()) != null)document.append(line + "\n");reader.close();} catch (MalformedURLException e) {System.out.println("Unable to connect to URL: " + urlString);} catch (IOException e) {System.out.println("IOException when connecting to URL: " + urlString);}return document.toString();}
?

?这是原来的方法。看了好多文章,终于明白怎么转换了。原来很简单的,就是当字节输入流conn.getInputStream()转为字符InputStreamReader时候,加上原来的字符集编码就可以了。因为在java内存里面保存的都是统一编码,InputStreamReader会自动转换

为统一编码的。所以这样改

?

BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));

这样就解决了问题。真是踏破铁鞋无觅处,得来全不费工夫。

关于字符集的,大家可以看看这篇文章,说得很清楚。如果遇到其他字符集问题,估计都不难解决的。

http://jiangzhengjun.iteye.com/blog/512072

?

热点排行