一、初识HttpClient
HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
用来发送http请求或者解析http响应。
官网地址:http://hc.apache.org/index.html
特点:
-
基于标准、纯净的Java语言。实现了Http1.0和Http1.1
-
以可扩展的面向对象的结构实现了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)
-
支持HTTPS协议。(https=http+ssl)
-
通过Http代理建立透明的连接。
-
自动处理Set-Cookie中的Cookie。
二、HttpClient请求
在使用之前,需要导包,使用maven:
<!-- 引入HttpClient依赖 -->
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents.client5/httpclient5 -->
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.2.1</version>
</dependency>
测试代码如下:
package com.leyou.httpdemo;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
public class HTTPTest {
CloseableHttpClient httpClient; //声明HttpClient
/**
* 执行请求之前先初始化 创建HttpClient实例
*/
@Before
public void init() {
httpClient = HttpClients.createDefault();
}
@Test
public void testGet() throws IOException {
HttpGet request = new HttpGet("http://www.baidu.com");
String response = this.httpClient.execute(request, new BasicResponseHandler());
System.out.println("=======================================================");
System.out.println(response);
System.out.println("=======================================================");
}
@Test
public void testPost() throws IOException {
HttpPost request = new HttpPost("https://www.oschina.net/");
request.setHeader("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
String response = this.httpClient.execute(request, new BasicResponseHandler());
System.out.println("=======================================================");
System.out.println(response);
System.out.println("=======================================================");
}
@Test
public void testGetPojo() throws IOException {
HttpGet request = new HttpGet("http://localhost:8080/hello");
String response = this.httpClient.execute(request, new BasicResponseHandler());
System.out.println("=======================================================");
System.out.println(response);
System.out.println("=======================================================");
}
}