package zs.payment.utils; import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import org.apache.http.client.HttpClient; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContexts; import org.apache.http.ssl.TrustStrategy; import org.springframework.http.*; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import javax.net.ssl.SSLContext; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.Map; @Slf4j public class HttpUtil { public static String restTemplateGet(String url, Map params) { try { // 创建忽略SSL验证的RestTemplate TrustStrategy acceptingTrustStrategy = new TrustStrategy() { @Override public boolean isTrusted(java.security.cert.X509Certificate[] chain, String authType) { return true; } }; SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(connectionSocketFactory).build(); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient); RestTemplate restTemplate = new RestTemplate(factory); // 构建URL UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(url); if (params != null) { for (Map.Entry entry : params.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (key != null && value != null) { uriBuilder.queryParam(key, value.toString()); } } } String finalUrl = uriBuilder.toUriString(); log.info("GET_URL====>{}", finalUrl); HttpHeaders headers = new HttpHeaders(); HttpEntity entity = new HttpEntity<>(headers); ResponseEntity rsp = restTemplate.exchange( finalUrl, HttpMethod.GET, entity, String.class ); return rsp.getBody(); } catch (Exception e) { log.error("HTTP请求失败: {}", e.getMessage()); throw new RuntimeException("网络请求异常", e); } } /** * get请求带token,参数入body,json * @param url * @param params * @param extraHeaders * @return */ public static String restTemplateGet(String url, Map params, Map extraHeaders) { try { // 创建忽略SSL验证的RestTemplate TrustStrategy acceptingTrustStrategy = new TrustStrategy() { @Override public boolean isTrusted(java.security.cert.X509Certificate[] chain, String authType) { return true; } }; SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(connectionSocketFactory).build(); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient); RestTemplate restTemplate = new RestTemplate(factory); // 构建URL UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(url); if (params != null) { for (Map.Entry entry : params.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (key != null && value != null) { uriBuilder.queryParam(key, value.toString()); } } } String finalUrl = uriBuilder.toUriString(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAcceptCharset(Collections.singletonList(StandardCharsets.UTF_8)); if (extraHeaders != null) { extraHeaders.forEach(headers::set); } HttpEntity request = new HttpEntity<>(headers); ResponseEntity rsp = restTemplate.exchange( finalUrl, HttpMethod.GET, request, String.class ); return rsp.getBody(); } catch (Exception e) { log.error("HTTP请求失败: {}", e.getMessage()); throw new RuntimeException("网络请求异常", e); } } /** * post 请求,支持自定义额外请求头 * @param url * @param params * @param extraHeaders 额外请求头(如 x-token) * @return */ public static String restTemplatePost(String url, Map params, Map extraHeaders) { try { TrustStrategy acceptingTrustStrategy = (chain, authType) -> true; SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(connectionSocketFactory).build(); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient); RestTemplate restTemplate = new RestTemplate(factory); restTemplate.getMessageConverters().removeIf(converter -> converter instanceof StringHttpMessageConverter); restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8)); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAcceptCharset(Collections.singletonList(StandardCharsets.UTF_8)); if (extraHeaders != null) { extraHeaders.forEach(headers::set); } String jsonBody = new JSONObject(params).toJSONString(); log.info("POST_URL====>{}, body====>{}", url, jsonBody); HttpEntity request = new HttpEntity<>(jsonBody, headers); ResponseEntity rsp = restTemplate.exchange(url, HttpMethod.POST, request, String.class); return rsp.getBody(); } catch (Exception e) { log.error("HTTP POST请求失败: {}", e.getMessage()); throw new RuntimeException("网络请求异常", e); } } /** * post 请求,请求头=application/json * @param url * @param params * @return */ public static String restTemplatePost(String url, Map params) { try { // 创建忽略SSL验证的RestTemplate TrustStrategy acceptingTrustStrategy = (chain, authType) -> true; SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(connectionSocketFactory).build(); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient); RestTemplate restTemplate = new RestTemplate(factory); // 配置UTF-8编码的消息转换器 restTemplate.getMessageConverters().removeIf(converter -> converter instanceof StringHttpMessageConverter); restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8)); // 设置请求头 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAcceptCharset(Collections.singletonList(StandardCharsets.UTF_8)); // 添加Accept-Charset,解决中文乱码问题 // 将参数转换为JSON字符串 String jsonBody = new JSONObject(params).toJSONString(); log.info("POST_URL====>{}, body====>{}", url, jsonBody); HttpEntity request = new HttpEntity<>(jsonBody, headers); ResponseEntity rsp = restTemplate.exchange( url, HttpMethod.POST, request, String.class ); return rsp.getBody(); } catch (Exception e) { log.error("HTTP POST请求失败: {}", e.getMessage()); throw new RuntimeException("网络请求异常", e); } } /** * POST 请求,Content-Type: application/x-www-form-urlencoded(表单格式) * @param url * @param params * @return */ public static String restTemplatePostCurl(String url, Map params) { try { TrustStrategy acceptingTrustStrategy = (chain, authType) -> true; SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(connectionSocketFactory).build(); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient); RestTemplate restTemplate = new RestTemplate(factory); restTemplate.getMessageConverters().removeIf(converter -> converter instanceof StringHttpMessageConverter); restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8)); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); headers.setAcceptCharset(Collections.singletonList(StandardCharsets.UTF_8)); MultiValueMap formData = new LinkedMultiValueMap<>(); if (params != null) { params.forEach((k, v) -> formData.add(k, v == null ? "" : v.toString())); } log.info("POST_CURL_URL====>{}, body====>{}", url, formData); HttpEntity> request = new HttpEntity<>(formData, headers); ResponseEntity rsp = restTemplate.exchange(url, HttpMethod.POST, request, String.class); return rsp.getBody(); } catch (Exception e) { log.error("HTTP POST CURL请求失败: {}", e.getMessage()); throw new RuntimeException("网络请求异常", e); } } }