Skip to content
标签
工具
字数
750 字
阅读时间
4 分钟

一、概述

由 apache 推出的实现使用 java 代码完成请求/响应的一套 API 可以实现模拟浏览器发送请求及解析响应内容

常用的类

  • CloseableHttpClient :负责发送请求和接收响应.相当于 浏览器
  • HttpPost: 请求对象,所有请求信息都放入到这个对象中
  • HttpGet: get 方式的请求
  • CloseableHttpResponse: 响应对象,所有响应信息放入到 这个类
  • EntityUtils: 工具类,解析响应体

二、使用案例

2.1 添加依赖

xml
<dependency> 
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId> 
    <version>${httpclient-version}</version> 
</dependency>

2.2 getPost请求

java
// get请求
public void testHttpGet() throws Exception {
    // 第一步:把HttpClient使用的jar包添加到工程中。
    // 第二步:创建一个HttpClient的测试类
    // 第三步:创建测试方法。
    // 第四步:创建一个HttpClient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
    // 第五步:创建一个HttpGet对象,需要制定一个请求的url
    // 带参数方式构建uri
    //URI uri = new URIBuilder("https://www.baidu.com/s").setParameter("wd", "sousuo").build();
    HttpGet get = new HttpGet("http://www.sougou.com");
    
    // 构建请求配置信息
	RequestConfig config = RequestConfig.custom().setConnectTimeout(1000) // 创建连接的最长时间
			.setConnectionRequestTimeout(500) // 从连接池中获取到连接的最长时间
			.setSocketTimeout(10 * 1000) // 数据传输的最长时间
			.build();
	// 设置请求配置信息
	httpGet.setConfig(config);
    
    // 第六步:执行请求。
    CloseableHttpResponse response = httpClient.execute(get);
    // 状态码  正常响应为200
    //response.getStatusLine().getStatusCode();
    // 第七步:接收返回结果。HttpEntity对象。
    HttpEntity entity = response.getEntity();
    // 第八步:取响应的内容。
    String html = EntityUtils.toString(entity);
    System.out.println(html);
    // 第九步:关闭response、HttpClient。
    response.close();
    httpClient.close();
}

// post请求
public void testHttpPost() throws Exception {
    // 第一步:创建一个httpClient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
    // 第二步:创建一个HttpPost对象。需要指定一个url
    HttpPost post = new HttpPost("http://localhost:8082/posttest.html");
    // 设置User-Agent属性
	// httpPost.setHeader("User-Agent", "");
    // 第三步:创建一个list模拟表单,list中每个元素是一个NameValuePair对象
    List<NameValuePair> formList = new ArrayList<>();
    formList.add(new BasicNameValuePair("name", "张三"));
    formList.add(new BasicNameValuePair("pass", "1243"));
    // 第四步:需要把表单包装到Entity对象中。StringEntity
    StringEntity entity = new UrlEncodedFormEntity(formList, "utf-8");
    post.setEntity(entity);
    // 第五步:执行请求。
    CloseableHttpResponse response = httpClient.execute(post);
    // 第六步:接收返回结果
    HttpEntity httpEntity = response.getEntity();
    // 二进制资源
    //response.getEntity().writeTo(outstream);
    String result = EntityUtils.toString(httpEntity);
    System.out.println(result);
    // 第七步:关闭流。
    response.close();
    httpClient.close();
}

2.3 连接池调用

java
public static void main(String[] args) throws Exception {
	// 创建连接池管理器
	PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();

	// 设置最大连接数
	cm.setMaxTotal(200);
	// 设置每个主机的并发数
	cm.setDefaultMaxPerRoute(20);
    
    // 关闭失效连接
	cm.closeExpiredConnections();

	doGet(cm);
	doGet(cm);
}

private static void doGet(PoolingHttpClientConnectionManager cm) throws Exception {
	// 获取连接
	CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();

	// 声明访问地址
	HttpGet httpGet = new HttpGet("https://www.autohome.com.cn/bestauto/");

	CloseableHttpResponse response = null;
	try {
		// 发起请求
		response = httpClient.execute(httpGet);

		// 判断状态码是否是200
        if (response.getStatusLine().getStatusCode() == 200) {
			// 解析数据
			String content = EntityUtils.toString(response.getEntity(), "UTF-8");
			System.out.println(content.length());
		}
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} finally {
		// 释放连接
		if (response != null) {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			// 不能关闭HttpClient
			// httpClient.close();
		}
	}
}