pom
<dependency> <groupId>org.apache.httpcomponents.client5</groupId> <artifactId>httpclient5</artifactId> <version>5.1.3</version> </dependency>
菜
package com.xcg.webapp.Common; import org.apache.commons.lang3.StringUtils; import org.apache.hc.client5.http.ClientProtocolException; import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.classic.methods.HttpPost; import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.entity.UrlEncodedFormEntity; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.HttpStatus; import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.http.io.entity.StringEntity; import org.apache.hc.core5.http.message.BasicNameValuePair; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Base64; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.zip.GZIPOutputStream; /** * https://blog.csdn.net/HIGK_365/article/details/136985075 */ public final class HttpRestUtil { //设置字符编码 private static final String CHARSET_UTF8 = "UTF-8"; /** * 发送HTTP POST请求,参数为JSON格式。 * 此方法用于将JSON格式的字符串作为请求体发送到指定的URL,并接收响应。 * * @param url 请求的URL地址。不能为空。 * @param jsonData 请求的参数,应为符合JSON格式的字符串。 * @param headParams 请求的头部参数,以键值对形式提供。可以为空,但如果非空,则添加到请求头中。 * @return 服务器响应的字符串形式内容。如果请求失败,则可能返回null。 * throws BusinessException 当发生不支持的编码、客户端协议错误或IO异常时抛出。 */ public static String post(String url, String jsonData, Map<String, String> headParams) throws Exception { String result = null; // 创建HTTP客户端实例 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; try { // 创建HTTP POST请求对象 HttpPost httpPost = new HttpPost(url); // 配置请求和传输超时时间 RequestConfig requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(100, TimeUnit.SECONDS) .build(); httpPost.setConfig(requestConfig); // 将JSON字符串参数转换为StringEntity,并设置请求实体 httpPost.setEntity(new StringEntity(jsonData, ContentType.create("application/json", CHARSET_UTF8))); // 如果存在头部参数,则添加到请求头中 if (headParams != null && !headParams.isEmpty()) { for (Map.Entry<String, String> entry : headParams.entrySet()) { httpPost.addHeader(entry.getKey(), entry.getValue()); } } // 执行请求并获取响应 response = httpClient.execute(httpPost); // 检查响应状态码 int statusCode = response.getCode(); if (HttpStatus.SC_OK != statusCode) { httpPost.abort(); throw new RuntimeException("HttpClient,error status code :" + statusCode); } // 从响应中获取内容并转换为字符串 var entity = response.getEntity(); if (null != entity) { result = EntityUtils.toString(entity, CHARSET_UTF8); } EntityUtils.consume(entity); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { //释放资源 release(response, httpClient); } return result; } /** * get请求 * https://blog.csdn.net/Barry_Li1949/article/details/134641891 */ public static String get(String urlWithParams) throws Exception { return get(urlWithParams, null, null); } public static String get(String url, Map<String, String> params, Map<String, String> headParams) throws Exception { String result = null; // 创建HTTP客户端实例 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String paramStr = null; try { // 构建请求参数列表 List<BasicNameValuePair> paramsList = new ArrayList<>(); if (params != null) { for (Map.Entry<String, String> entry : params.entrySet()) { paramsList.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } // 将参数列表转换为字符串形式,用于拼接到URL后 paramStr = EntityUtils.toString(new UrlEncodedFormEntity(paramsList)); } // 拼接参数到URL StringBuffer sb = new StringBuffer(); sb.append(url); if (!StringUtils.isBlank(paramStr)) { sb.append("?"); sb.append(paramStr); } // 创建HTTP GET请求对象 HttpGet httpGet = new HttpGet(sb.toString()); // 配置请求和传输超时时间 RequestConfig requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(100, TimeUnit.SECONDS) .build(); httpGet.setConfig(requestConfig); // 如果存在头部参数,则添加到请求头中 if (headParams != null && !headParams.isEmpty()) { for (Map.Entry<String, String> entry : headParams.entrySet()) { httpGet.addHeader(entry.getKey(), entry.getValue()); } } // 执行请求并获取响应 response = httpClient.execute(httpGet); // 检查响应状态码 int statusCode = response.getCode(); if (HttpStatus.SC_OK != statusCode) { httpGet.abort(); throw new RuntimeException("HttpClient,error status code :" + statusCode); } // 从响应中获取内容并转换为字符串 var entity = response.getEntity(); if (null != entity) { result = EntityUtils.toString(entity, CHARSET_UTF8); } EntityUtils.consume(entity); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { //释放资源 release(response, httpClient); } return result; } /** * 释放资源,httpResponse为响应流,httpClient为请求客户端 */ private static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException { if (httpResponse != null) { httpResponse.close(); } if (httpClient != null) { httpClient.close(); } } }