Java请求Http接口常用的方式有三种,如下表
| 序号 | 工具 | 描述 | 应用案例 |
|---|---|---|---|
| 1 | URLConnection | Java原生,java.net.URLConnection | https://blog.csdn.net/Xin_101/article/details/122440247 |
| 2 | HttpURLConnection | Java原生,java.net.HttpURLConnection | https://blog.csdn.net/Xin_101/article/details/122449254 |
| 3 | httpclient | 第三方工具,org.apache.httpcomponents | https://blog.csdn.net/Xin_101/article/details/122449693 |
本章讲解httpclient请求接口。
1.2 httpclient原Apache httpclient通用依赖为:commons-httpclient,现已将该功能迁移到:org.apache.httpcomponents
commons-httpclient commons-httpclient 3.1
Maven仓库告知如下:
2 接口org.apache.httpcomponents httpclient 4.5.13
表单接口:
package com.monkey.java_study.web;
import com.google.gson.Gson;
import com.monkey.java_study.common.entity.PageEntity;
import org.apache.http.HttpEntity;
import org.apache.http.NamevaluePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNamevaluePair;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.*;
public class HttpClientTest {
private static final Logger logger = LogManager.getLogger(HttpClientTest.class);
public static String doGet(String url) {
try {
// 创建客户端
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// 建立连接
HttpGet httpGet = new HttpGet(url);
// 请求配置:超时时间,单位:毫秒
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
httpGet.setConfig(requestConfig);
// 设置请求头:内容类型
httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");
return getResponse(httpClientBuilder, httpGet);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static String doPostFormData(String url, Map paramMap) {
try {
// 创建客户端
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// 建立连接
HttpPost httpPost = new HttpPost(url);
// 请求配置:超时时间,单位:毫秒
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
httpPost.setConfig(requestConfig);
// 设置请求头:内容类型
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
if (Objects.nonNull(paramMap) && !paramMap.isEmpty()) {
List formDataList = new ArrayList<>();
Set> entrySet = paramMap.entrySet();
for (Map.Entry mapEntry : entrySet) {
formDataList.add(new BasicNamevaluePair(mapEntry.getKey(), mapEntry.getValue().toString()));
}
httpPost.setEntity(new UrlEncodedFormEntity(formDataList, "UTF-8"));
}
return postResponse(httpClientBuilder, httpPost);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static String doPostJson(String url, String params) {
try {
// 创建客户端
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// 建立连接
HttpPost httpPost = new HttpPost(url);
// 请求配置:超时时间,单位:毫秒
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
httpPost.setConfig(requestConfig);
// 设置请求头:内容类型
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
StringEntity stringEntity = new StringEntity(params);
stringEntity.setContentType("text/json");
httpPost.setEntity(stringEntity);
return postResponse(httpClientBuilder, httpPost);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static String getResponse(HttpClientBuilder httpClientBuilder, HttpGet httpGet) {
try (CloseableHttpResponse closeableHttpResponse = httpClientBuilder.build().execute(httpGet)) {
HttpEntity httpEntity = closeableHttpResponse.getEntity();
return EntityUtils.toString(httpEntity, "UTF-8");
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static String postResponse(HttpClientBuilder httpClientBuilder, HttpPost httpPost) {
try (CloseableHttpResponse closeableHttpResponse = httpClientBuilder.build().execute(httpPost)) {
HttpEntity httpEntity = closeableHttpResponse.getEntity();
return EntityUtils.toString(httpEntity, "UTF-8");
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static void main(String[] args) {
// GET:请求
String getUrl = "http://localhost:9121/api/v1/mongodb/read?userId=0x001";
String getResponse = doGet(getUrl);
logger.info(">>>>>>>>>Get response:{}", getResponse);
// POST:请求携带form-data参数
String postFormDataUrl = "http://localhost:9121/api/v1/parameter/annotation/form-data";
Map mapFormData = new HashMap<>();
mapFormData.put("name", "xiaohong");
String formDataResponse = doPostFormData(postFormDataUrl, mapFormData);
logger.info(">>>>>>>>>Post form data response:{}", formDataResponse);
// POST:请求携带JSON参数
String postUrl = "http://localhost:9121/api/v1/mongodb/page";
// 入参实体
PageEntity pageEntity = new PageEntity(1, 2);
Gson gson = new Gson();
// 实体转JSON字符串
String jsonString = gson.toJson(pageEntity);
String postResponse = doPostJson(postUrl, jsonString);
logger.info(">>>>>>>>>>Post json response:{}", postResponse);
}
}
2.2 测试



