访问网络资源,并显示成中文,解决中文乱码问题.
2011-05-13 13:22
351 查看
访问google的地图数据网站,取得json文件,并对其进行解析. 取出其中的位置信息数据.
解决问题的关键是:直接取得字节流,不要使用编码。
使用ByteArrayOutputStream
StringBuilder stringBuilder = new StringBuilder();
try {
String strUrl = String
.format(
"http://maps.google.com/maps/api/geocode/json?latlng=%s&sensor=true",
latlng);
Log.v(TAG, " strUrl = " + strUrl);
URL googleUrl = new URL(strUrl);
int count = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
HttpURLConnection http = (HttpURLConnection) googleUrl
.openConnection();
http.setConnectTimeout(5 * 1000);
http.setRequestProperty("Accept-Language", "zh-CN");//向网站发起中文请求
http.setRequestProperty("Charset", "UTF-8"); //设置本地字符集
InputStream inStream = http.getInputStream(); //取得字节流
byte[] buf = new byte[512];
int ch = -1;
while ((ch = inStream.read(buf)) != -1) {
baos.write(buf, 0, ch); //把字节流以字节的方式写入ByteArrayOutputStream 中。
count = count + ch;
}
stringBuilder.append(new String(baos.toByteArray(), "UTF-8")); //对取得的字节流以UTF-8解码。
解决问题的关键是:直接取得字节流,不要使用编码。
使用ByteArrayOutputStream
StringBuilder stringBuilder = new StringBuilder();
try {
String strUrl = String
.format(
"http://maps.google.com/maps/api/geocode/json?latlng=%s&sensor=true",
latlng);
Log.v(TAG, " strUrl = " + strUrl);
URL googleUrl = new URL(strUrl);
int count = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
HttpURLConnection http = (HttpURLConnection) googleUrl
.openConnection();
http.setConnectTimeout(5 * 1000);
http.setRequestProperty("Accept-Language", "zh-CN");//向网站发起中文请求
http.setRequestProperty("Charset", "UTF-8"); //设置本地字符集
InputStream inStream = http.getInputStream(); //取得字节流
byte[] buf = new byte[512];
int ch = -1;
while ((ch = inStream.read(buf)) != -1) {
baos.write(buf, 0, ch); //把字节流以字节的方式写入ByteArrayOutputStream 中。
count = count + ch;
}
stringBuilder.append(new String(baos.toByteArray(), "UTF-8")); //对取得的字节流以UTF-8解码。
相关文章推荐
- SVN+Apache在windows下http访问 显示中文乱码问题的解决方法
- 解决Toad的中文显示乱码问题
- Sublime Text 2支持GB2312和GBK,解决中文显示乱码问题
- Android 与 PC网络通信之中文乱码问题解决
- [ubuntu]如何解决中文显示乱码的问题
- chm文件的中文显示乱码问题解决
- 今天在网络上找到了一个比较好的解决Rhythmbox中文乱码的问题的方法
- JSP中乱码问题解决(一、JSP页面显示乱码,二、表单提交中文时出现乱码,三、数据库连接出现乱码,四、数据库的显示乱码 )
- zxing 黑屏 无法显示图像问题 及中文乱码问题解决
- Sublime Text 2支持GB2312和GBK,解决中文显示乱码问题
- [Ubuntu--VIM]vim打开代码文档中文注释显示为乱码的问题解决
- emma中文显示乱码问题解决
- 解决Zend Development中显示中文乱码的问题
- 解决弹出OUTLOOK显示繁体中文乱码的问题
- 解决Xshell显示中文乱码的问题
- SecureCRT连接Linux,终端显示中文乱码问题,全方面解决
- ubuntu12.04解决gedit中文显示乱码问题
- MySQL 中文显示乱码以及中文查询条件返回0条结果的问题解决
- Jira饼图上中文乱码,显示为“口”的解决办法,以及问题附件中文名时无法打开终极办法
- MySQL 中文显示乱码问题解决汇总