- 介绍
HttpClient是Apache公司的产品,是Http Components下的一个子组件
2. 特点
1. 基于标准、纯净的java语言。实现了Http1.0、Http1.1。
2. 可以扩展的面向对象的结构实现了http的全部方法(get,post,put,delete,head,options,andtrace)
3.支持Https协议。
4.通过http代理建议透明的连接。
5. 自动处理Set-cookie中的cookie。
3.使用 -- 创建httpClient客户端
public class HttpTests{
CloseableHttpClient httpClient;
@Before
public void init(){
// 创建httpClient的客户端
httpClient = HttpClients.createDefault();
}
}
3.1 发起get请求
@Test
public void testGet() throws IOException{
// 发起什么请求就new什么, 比如new HttpPost 等等....
HttpGet request= new HttpGet('http://www.baidu.com');
// 执行请求
String response = this.httpClient.execute(request,new BasicResponseHandler());
system.out.println(response);
}
3.2 发起post请求
@Test
public void testPost() throws IOException{
// 发起什么请求就new什么, 比如new HttpPost 等等....
HttpPost request= new HttpPost('https://my.oschina.net');
// 设置请求头,欺骗一下开源中国。因为开源中国限制爬虫访问
request.setHeader("user-agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
// 执行请求
String response = this.httpClient.execute(request,new BasicResponseHandler());
system.out.println(response);
}
3.3 使用Get请求访问自己的服务器,实现远程调用
@Test
public void testGetPojo() throws IOException{
// 发起请求 // http://localhost:8080/hello 服务器地址
HttpGet request= new HttpGet('http://localhost:8080/hello');
// 执行请求,获得json数据
String response = this.httpClient.execute(request,new BasicResponseHandler());
// json数据转为对象数据便可, 可使用ObjectMapper
system.out.println(response);
}