本帖最后由 NullPointer 于 2016-12-28 18:04 编辑
[Asm] 纯文本查看 复制代码 public static void main(String[] args) {
//请求的url(前面加http:// 不然会报错)
String url="http://www.baidu.com";
//1.创建HttpClient对象 这里使用默认的配置的httpclient
CloseableHttpClient client = HttpClients.createDefault();
//2.创建某种请求方法的实例。这里使用get方法
HttpGet httpGet = new HttpGet(url);
InputStream inputStream = null;
CloseableHttpResponse response = null;
try {
//3.执行请求,获取响应
response = client.execute(httpGet);
//看请求是否成功,这儿打印的是http状态码
System.out.println(response.getStatusLine().getStatusCode());
//4.获取响应的实体内容,就是我们所要抓取得网页内容
HttpEntity entity = response.getEntity();
//5.将其打印到控制台上面,这里使用EntityUtils(也可以用inputStream)
if (entity != null) {
System.out.println(EntityUtils.toString(entity, "utf-8"));
}
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
} finally {
//6.关闭连接,释放资源(很重要)
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|