1.依赖
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.7</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
2.配置类
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLContext;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setConnectTimeout(3000);
factory.setReadTimeout(5000);
return factory;
}
/**
* 忽略证书配置
*/
public static HttpComponentsClientHttpRequestFactory generateHttpRequestFactory()
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true;
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
new NoopHostnameVerifier());
HttpClientBuilder httpClientBuilder = HttpClients.custom();
httpClientBuilder.setSSLSocketFactory(connectionSocketFactory);
CloseableHttpClient httpClient = httpClientBuilder.build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setHttpClient(httpClient);
return factory;
}
}
3.工具类:注意:该工具类在某些情况下可能存在序列化问题,建议使用下文优化过后的工具类!!!而且下文优化过后的工具类日志打印更加友好。
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import javax.servlet.http.HttpServletRequest;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
/**
* Http请求工具类
*
* @author djh
* @since 2023-09-28
*/
@Component
@Slf4j
public class HttpUtil {
/**
* 跳过证书验证
*/
RestTemplate restTemplateHttps = new RestTemplate(RestTemplateConfig.generateHttpRequestFactory());
@Autowired
private HttpServletRequest request;
public HttpUtil() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
}
/**
* 模拟Post请求
*/
public void postTest() {
// 从请求头获取token
String token = request.getHeader("token");
// 请求地址
String url = "http://xxx/xxx";
// 构建请求body参数,即请求体的JSON实体类,这里简单模拟
HashMap<String, String> map = new HashMap<>();
map.put("id", "1");
map.put("name", "tom");
// 添加请求头
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
// 组装请求头和参数
HttpEntity<Map<String, String>> formEntity = new HttpEntity<>(map, headers);
// 发起post请求
ResponseEntity<String> stringResponseEntity = post(url, formEntity);
// 获取返回体,这个就是请求接口返回的JSON数据
String body = stringResponseEntity.getBody();
// 解析body,反序列化成需要的对象即可
Map mapResponse = JSON.parseObject(body, Map.class);
}
/**
* 发送Post请求
*/
private ResponseEntity<String> post(String url, HttpEntity formEntity) {
ResponseEntity<String> stringResponseEntity = null;
log.info("调用{}接口的请求参数为:{}", url, JSON.toJSONString(formEntity));
try {
stringResponseEntity = restTemplateHttps.postForEntity(url, formEntity, String.class);
} catch (Exception e) {
log.error("HttpUtil请求{}接口失败,失败原因:{}", url, e.toString());
}
log.info("调用{}接口的响应结果为:{}", url, JSON.toJSONString(stringResponseEntity));
return stringResponseEntity;
}
/**
* 模拟Get请求
*/
public void getTest() {
String url = "https://xxx";
// 获得的String 对象就是接口返回的JSON数据
String forObject = restTemplateHttps.getForObject(url, String.class);
// 解析JSON
Map map = JSON.parseObject(forObject, Map.class);
}
}
---------------------------------------------------更新分割线---------------------------------------------------
在另一个项目拷贝使用该工具类时,出现了序列化问题,报错信息如下:
org.springframework.web.client.RestClientException: Error while extracting response for type [class java.lang.String] and content type [application/json;charset=UTF-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `java.lang.String` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.lang.String` out of START_OBJECT token
at [Source: (PushbackInputStream); line: 1, column: 1]
大抵可能是这一行代码出现问题:
原因可能是项目里所使用的序列化底层实现出现冲突,故需要修改一下。也建议采用如下工具类代码,避免出现序列化转换问题。代码如下:
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import javax.servlet.http.HttpServletRequest;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
/**
* Http请求工具类
*
* @author djh
* @since 2023-09-28
*/
@Component
@Slf4j
public class HttpUtil {
/**
* 跳过证书验证
*/
RestTemplate restTemplateHttps = new RestTemplate(RestTemplateConfig.generateHttpRequestFactory());
@Autowired
private HttpServletRequest request;
public HttpUtil() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
}
/**
* 模拟Post请求
*/
public void postTest() {
// 从请求头获取token
String token = request.getHeader("token");
// 请求地址
String url = "http://xxx/xxx";
// 构建请求body参数,即请求体的JSON实体类,这里简单模拟
HashMap<String, String> map = new HashMap<>();
map.put("id", "1");
map.put("name", "tom");
// 添加请求头
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
// 组装请求头和参数
HttpEntity<Map<String, String>> formEntity = new HttpEntity<>(map, headers);
// 发起post请求
ResponseEntity<Object> stringResponseEntity = post(url, formEntity);
// 获取返回体,这个就是请求接口返回的JSON数据
String body = JSON.toJSONString(stringResponseEntity.getBody());
// 解析body,反序列化成需要的对象即可
Map mapResponse = JSON.parseObject(body, Map.class);
}
/**
* 发送Post请求
*/
private ResponseEntity<Object> post(String url, HttpEntity formEntity) {
ResponseEntity<Object> stringResponseEntity = null;
log.info("调用{}接口的请求参数为:{}", url, JSON.toJSONString(formEntity.getBody()));
try {
stringResponseEntity = restTemplateHttps.postForEntity(url, formEntity, Object.class);
} catch (Exception e) {
log.error("HttpUtil请求{}接口失败,失败原因:{}", url, e.toString());
}
if (stringResponseEntity != null) {
log.info("调用{}接口的响应结果为:{}", url, JSON.toJSONString(stringResponseEntity.getBody()));
}
return stringResponseEntity;
}
/**
* 模拟Get请求
*/
public void getTest(String url) {
// 获得的Object 对象就是接口返回的JSON数据,这里用Object接收,自己转JSON。
// 如果直接用String,在某些情况下会序列化失败,原因可能是某些序列化的实现有冲突。
Object forObject = restTemplateHttps.getForObject(url, Object.class);
// 转化JSON
String jsonStr = JSON.toJSONString(forObject);
// 解析JSON
Map map = JSON.parseObject(jsonStr, Map.class);
}
}
核心改动点如图:
修改出参,这样子可以避免序列化失败的问题,Get请求同理:
经过测试,可以正常使用。