一、介绍
HttpClient是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包。
HttpClient 是一个HTTP通信库、一个工具包,它只提供一个通用浏览器应用程序所期望的功能子集,与浏览器相比是没有界面的。
二、添加依赖
<!--httpclient-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version>
</dependency>
二、测试
我们先创建一个用于测试的实体类
package com.example.fastjsondemo.model;
import lombok.Data;
/**
* @author qx
* @date 2023/8/29
* @des 测试的实体类
*/
@Data
public class Map {
private String status;
private String info;
private String infocode;
private String province;
private String city;
private String adcode;
private String rectangle;
}
测试Get请求
/**
* 测试get请求
*/
@Test
void testGet() throws IOException {
String url = "https://restapi.amap.com/v3/ip?key=0113a13c88697dcea6a445584d535837&ip=171.110.83.78";
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = client.execute(httpGet);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String json = EntityUtils.toString(response.getEntity());
Map map = JSONObject.parseObject(json, Map.class);
System.out.println(map);
}
}
执行Get请求输出:
Map(status=1, info=OK, infocode=10000, province=广西壮族自治区, city=梧州市, adcode=450400, rectangle=111.1604726,23.41005092;111.4408064,23.57943575)
测试Post请求
/**
* 测试Post请求
*
* @throws IOException
*/
@Test
void testPost() throws IOException {
CloseableHttpClient client = HttpClients.createDefault();
String url = "https://restapi.amap.com/v3/ip";
HttpPost httpPost = new HttpPost(url);
// 参数设置
List<NameValuePair> paramList = new ArrayList<>();
paramList.add(new BasicNameValuePair("key", "0113a13c88697dcea6a445584d535837"));
paramList.add(new BasicNameValuePair("ip", "171.110.83.78"));
// 设置httpPost使用的参数
httpPost.setEntity(new UrlEncodedFormEntity(paramList));
// 执行
CloseableHttpResponse response = client.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String json = EntityUtils.toString(response.getEntity());
Map map = JSONObject.parseObject(json, Map.class);
System.out.println(map);
}
}
执行Post请求输出
Map(status=1, info=OK, infocode=10000, province=广西壮族自治区, city=梧州市, adcode=450400, rectangle=111.1604726,23.41005092;111.4408064,23.57943575)