前言
下面介绍Apache HTTPClient 的使用方式。
依赖包
- httpclient-4.5.13.jar
- commons-codec-1.15.jar
- commons-logging-1.2.jar
- httpcore-4.4.15.jar
备注:依赖包可以去 maven仓库下载。
1、GET请求
// 创建客户端请求
CloseableHttpClient client = HttpClientBuilder.create().build();
// 创建GET请求
HttpGet get = new HttpGet("http://10.47.22.151:8100/api/Login/UserToken");
// 执行GET请求
CloseableHttpResponse response = client.execute(get);
try {
// 获取请求内容
HttpEntity entity = response.getEntity();
System.out.println(EntityUtils.toString(entity));
} finally {
if (response != null) {
response.close();
}
if (client != null) {
client.close();
}
}
2、POST
1)Params类型
// 创建客户端请求
CloseableHttpClient client = HttpClientBuilder.create().build();
// 创建POST请求
HttpPost post = new HttpPost("http://10.147.254.110:80/token");
// 拼接参数
List<NameValuePair> list = new ArrayList<>();
list.add(new BasicNameValuePair("userName", "rest"));
list.add(new BasicNameValuePair("password", "123456"));
list.add(new BasicNameValuePair("loginName", "jack"));
// 设置请求头
post.setHeader("Content-Type", "application/json");
// 设置请求参数
post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
// 执行请求
CloseableHttpResponse response = client.execute(post);
try {
// 获取请求内容
HttpEntity entity = response.getEntity();
System.out.println(EntityUtils.toString(entity));
} finally {
if (response != null) {
response.close();
}
if (client != null) {
client.close();
}
}
2)row类型
// 创建客户端请求
CloseableHttpClient client = HttpClientBuilder.create().build();
// 创建POST请求
HttpPost post = new HttpPost("http://10.147.254.110:80/seeyon/rest/token");
// 拼接参数
Map<String, String> rMap = new HashMap<>();
rMap.put("userName", "rest");
rMap.put("password", "991dfd4a-d7bb-4aa6-b04c-d1a1bff26d4f");
rMap.put("loginName", "lyb");
// 设置请求头
post.setHeader("Content-Type", "application/json");
// 设置请求参数
post.setEntity(new StringEntity(JSON.toJSONString(rMap)));
// 执行请求
CloseableHttpResponse response = client.execute(post);
try {
// 获取请求内容
HttpEntity entity = response.getEntity();
System.out.println(EntityUtils.toString(entity));
} finally {
if (response != null) {
response.close();
}
if (client != null) {
client.close();
}
}
以上 ·params· 和 ·raw· 是对应 postman中的两种传参方式。