java爬虫 抓取知乎,java爬虫抓取知乎推荐总是乱码

求助java爬虫抓取知乎推荐总是乱码

仿照http://blog.csdn.net/pleasecallmewhy/article/details/17630063写一个简单的抓取知乎推荐(http://www.zhihu.com/explore/recommendations)的爬虫,读出的网页源码总是乱码,而同样的代码读取别的网站都是正常的。是知乎网站本身做了什么限制吗?有人说知乎输出的内容是json格式,是否有关系?

爬虫代码如下:

package test;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.MalformedURLException;

import java.net.URL;

import java.net.URLConnection;

import java.util.regex.*;

public class Main {

static String sendGet(String url) throws IOException{

//String url="http://www.baidu.com";

String result="";

BufferedReader in=null;

try {

URL realUrl=new URL(url);

URLConnection connection=realUrl.openConnection();

connection.connect();

in= new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));

String line;

while ((line=in.readLine())!=null){

result+=line;

}

} catch (MalformedURLException e) {

System.out.print("发送GET请求出现异常!" + e);

// TODO Auto-generated catch block

e.printStackTrace();

}

finally{

try {

if (in != null) {

in.close();

}

} catch (Exception e2) {

e2.printStackTrace();

}

}

return result;

}

static String RegexString(String tartgetStr,String patterStr){

Pattern p=Pattern.compile(patterStr);

Matcher matcher=p.matcher(tartgetStr);

if (matcher.find()){

return matcher.group(1);

}

return "nothing";

}

public static void main(String[] args) throws IOException{

String url="http://www.zhihu.com/explore/recommendations";

String result=sendGet(url);

System.out.println(result);

}

}

输出的乱码是这种形式的:

1556546.gif

------解决思路----------------------

static String sendGet(String url) throws IOException {

// String url="http://www.baidu.com";

String result = "";

BufferedReader in = null ;

try {

URL realUrl = new URL(url);

URLConnection connection = realUrl.openConnection();

connection.connect();

InputStream urlStream = new GZIPInputStream(connection.getInputStream());

in = new BufferedReader(new InputStreamReader(urlStream,"utf-8"));

String line = "";

while ((line = in.readLine()) != null) {

System.out.println(line);

result += line;

}

} catch (MalformedURLException e) {

System.out.print("发送GET请求出现异常!" + e);

// TODO Auto-generated catch block

e.printStackTrace();

} finally {

try {

if (in != null) {

in.close();

}

} catch (Exception e2) {

e2.printStackTrace();

}

}

return result;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值