JAVA抓取网页json数据时打印结果乱码求帮助

WionWan 2015-07-21 03:53:05
最近做个小应用,需要抓取一个网站的数据没错就是B站。。。
然后我得到了b站的一段json数据网址,准备抓取下来做解析,但是呢,问题来了,我用以下方法抓取的时候,打印内容是乱码的,B站原来的数据是Unicode编码,我用了很多方法转换字符集都不能成功,各位大神支支招吧!写了
package com.dmj.test;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class Testbilibili {
public static void main(String[] args) {
InputStream iis=null;
try {
URL url=new URL("http://www.bilibili.com/index/rank/all-7-33.json");
url.openConnection();
iis=url.openStream();

byte[] bs=new byte[1024];
int length=0;
StringBuffer sb=new StringBuffer();
while((length=iis.read(bs,0,bs.length))!=-1){
sb.append(new String(bs,0,length));
}
System.out.println(sb.toString());
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
iis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

【以上方法乱码】
看了网上的教程,通过
String value=new String(sb.toString().getBytes("Unicode"),"utf-8");
System.out.println(value);

【以上方法乱码】依然不行。我换成 HttpURLConnection 抓取网页 设置
httpurlconnection.setRequestProperty("Content-type", "text/html");
httpurlconnection.setRequestProperty("Accept-Charset", "utf-8");
httpurlconnection.setRequestProperty("contentType", "utf-8");

【以上方法乱码】读取的依然乱码。
那么小弟在此请教各位,我想正确的抓取 http://www.bilibili.com/index/rank/all-7-33.json 这个网页的json数据打印下来不乱码或者显示正确的Unicode的也行只要不乱吗就好。。求支招。。。。如果可以您先试试方法成功了之后再告诉我一下,,。。小弟拜托各位啦。
...全文
293 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
ZZJune 2018-10-10
  • 打赏
  • 举报
回复
引用 2 楼 q583900890 的回复:
写快了,改一下sb.append(cbuf,0,len);


赞啊,
晴天_ccc 2015-07-22
  • 打赏
  • 举报
回复
写快了,改一下sb.append(cbuf,0,len);
晴天_ccc 2015-07-22
  • 打赏
  • 举报
回复
URL url = new URL("http://www.bilibili.com/index/rank/all-7-33.json");
		URLConnection conn = url.openConnection();
		conn.connect();

		GZIPInputStream gzipIs = new GZIPInputStream(conn.getInputStream());

		InputStreamReader isr = new InputStreamReader(gzipIs, "Utf-8");
		StringBuilder sb = new StringBuilder();
		char[] cbuf = new char[1024];
		int len = 0;
		while ((len = isr.read(cbuf)) != -1) {
			sb.append(cbuf);
		}

		System.out.println(sb.toString());
		gzipIs.close();
		isr.close();
数据加加过gzip压缩打过来的,需要用gzip流去读。

50,331

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧