求助 httpClient.execute 报空指针异常

一个人的朝圣丶 2017-07-14 05:05:08
talk is cheap


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)

...全文
1171 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
110成成 2017-07-14
  • 打赏
  • 举报
回复
你的private static HttpClient httpClient = null; httpClient 为空啊,你没有创建啊。
  • 打赏
  • 举报
回复
为什么entity是空的啊
李德胜1995 2017-07-14
  • 打赏
  • 举报
回复
25行httpClient为空。。。。

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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