62,615
社区成员
发帖
与我相关
我的任务
分享
package test;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
public class TestSpider {
//使用HttpClient创建一个客户端
private static HttpClient httpClient = null;
/**
* @param path 目标网页的链接
* @return 表示是否可读取页面
* @throws Exception IO异常
*/
public boolean downloadPage(String path) throws Exception {
InputStream is = null;
//创建一个HttpGet类,相当于在浏览器(HttpClient)中输入了一个地址
HttpGet httpGet = new HttpGet(path);
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if(entity!=null) {
is = entity.getContent();
}
int length;
byte[] tmp = new byte[2048];
while((length = is.read(tmp)) != -1) {
System.out.println(new String(tmp,0,length,"UTF-8"));
}
return false;
}
public static void main(String[] args) throws Exception {
TestSpider ts = new TestSpider();
ts.downloadPage("http://www.baidu.com");
}
}
Exception in thread "main" java.lang.NullPointerException
at test.TestSpider.downloadPage(TestSpider.java:25)
at test.TestSpider.main(TestSpider.java:43)