java爬虫篇第一章:HttpClient入门

学习资料:《自己动手写爬虫》、官方PDF。

 

看《自己动手写爬虫》这本书的时候,发觉里面代码都上年纪了,新的jar包已经不支持书上的代码了。本博从改第一个例子讲起。

 

旧代码(当然这段代码是执行不了的,所以就不贴全了):

 1 //创建一个客户端,类似于打开一个浏览器
 2 HttpClient httpclient=new HttpClient();
 3 
 4 //创建一个get 方法,类似于在浏览器地址栏中输入一个地址
 5 GetMethod getMethod=new GetMethod("http://www.blablabla.com");
 6 
 7 //回车,获得响应状态码
 8 int statusCode=httpclient.executeMethod(getMethod);
 9 
10 //查看命中情况,可以获得的东西还有很多,比如head、cookies 等
11 System.out.println("response=" + getMethod.getResponseBodyAsString());
12 
13 //释放
14 getMethod.releaseConnection();

以上的代码包含几个步骤,分别是:创建客户端;用get方法对“http://www.blablabla.com"网址发起请求;获得返回数据后;最后进行句柄释放。

 

新代码:

①:pom文件依赖部分

<dependencies>
  <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.8</version>
</dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.jsoup</groupId>
      <artifactId>jsoup</artifactId>
      <version>1.12.1</version>
    </dependency>
  </dependencies>

 

②:代码部分

package home.spider;

import java.io.IOException;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args ) throws IOException{//创建一个get 方法,类似于在浏览器地址栏中输入一个地址
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet("http://www.blablabla.com");
        //回车,获得响应状态码
        CloseableHttpResponse response = httpclient.execute(httpget);
        //查看命中情况,可以获得的东西还有很多,比如head、cookies 等
        System.out.println("response:" + response.toString());
        //释放
        httpget.releaseConnection();
}

以上就是对应旧代码的变更点哦~

posted @ 2019-06-10 22:41  天叔  阅读(636)  评论(0编辑  收藏  举报