直接上代码:
public Object getResponse(String apiToken, String url, Class o)
throws Exception {
RestTemplate restTemplate = new RestTemplate(RestTemplateConfig.generateHttpRequestFactory());
HttpHeaders headers = new HttpHeaders();
headers.add("API-TOKEN", apiToken);
headers.add("Content-Type", " application/json");
HttpEntity<String> formEntity = new HttpEntity<String>(null, headers);
ResponseEntity<Class> response =
restTemplate.exchange(
url, // 获取资源的地址
HttpMethod.GET,
formEntity,
o // 返回类型设为class
);
return response;
}
用该方法拿到的返回结果是中文乱码,在之前的项目未出现,但是在这个项目里同样的代码,调用同样的url返回的是乱码(内部原因还没排查),但是通过 restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));加了该转换代码之后问题解决。
加完之后变为如下:
public Object getResponse(String apiToken, String url, Class o)
throws Exception {
RestTemplate restTemplate = new RestTemplate(RestTemplateConfig.generateHttpRequestFactory());
//此处加编码格式转换
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
HttpHeaders headers = new HttpHeaders();
headers.add("API-TOKEN", apiToken);
headers.add("Content-Type", " application/json");
HttpEntity<String> formEntity = new HttpEntity<String>(null, headers);
ResponseEntity<Class> response =
restTemplate.exchange(
url, // 获取资源的地址
HttpMethod.GET,
formEntity,
o // 返回类型设为class
);
return response;
}
初始换RestTemplate的时候用的自定义RestTemplateConfig.generateHttpRequestFactory(),该处理中增加了跳过对https的证书校验,具体代码在https://blog.csdn.net/weixin_45658376/article/details/119035748?spm=1001.2014.3001.5501中已详细说明。