JAVA爬虫的介绍--HttpClient|青训营笔记

88 阅读1分钟

这是我参与「第三届青训营 -后端场」笔记创作活动的第3篇笔记,HttpClient作为Apache的开源项目,以其灵活性和高效性,以及提供给用户丰富的的编程工具包,成为众多使用者的首选内容之一。一般我们使用HttpClient发送GET请求,一般需要如下几步即可。

首先进行的是工程的创建,需要建立一个mavern工程,将HttpClient需要的的jar包添加到工程中,

<mvnrepository.com/artifact/or… >

       < dependency>

            < groupId>org.apache.httpcomponents< /groupId>

            < artifactId>httpcore< /artifactId>

            < version>4.4.10< /version>

        < /dependency>

        < mvnrepository.com/artifact/or… >

        

            < groupId>org.apache.httpcomponents< /groupId>

             < artifactId>httpclient</ artifactId>

            < version>4.5.6</ version>

        < /dependency>

然后是发送到GET的请求方法:

1) 创建一个HttpClient对象(CloseableHttpClient),HittpClients创建。(相当于打开浏览器)

closeableHttpclient httpclient_= Httpclients.createDefault();

2) 创建一个HttpGet对象,相当于是一个get请求,构造参数中设置请求的url。

/ /2)创建一个HttpGet对象,相当于是一个get请求,构造参数中设置请求的urL。HttpGet get = new HttpGet( uri: "http : / /wwns.itcast.cn?);

3) 使用HttpClient对象发送请求。

closeableHttpResponse response = httpclient.execute(get);

4)得到服务端的响应。取服务端响应的htmL

StatusLinestatusLine = response.getStatusLine();

system.out.println(statusLine) ;

int status  Code=statusLine   .getstatusCode();

System.out.print1n(statusCode) ;

HttpEntity entity = response.getEntity();

string html = Entityutils.toString(entity,defaultCharset : "utf-8"");

5)打印htmL

System.out.print1n(html )

6) 关闭流

response.close();httpClient.close();