0%

restTemplate常见操作

常见的restTemplate操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//三种方式 xxForObject、xxForEntity、exchange

//封装请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);//封装请求类型
headers.add("Accept", MediaType.APPLICATION_JSON.toString());//封装可接收类型,"Accept", MediaType.APPLICATION_JSON_VALUE
//封装请求参数
ObjectMapper objectMapper = new ObjectMapper();
String jsonStr = objectMapper.writeValueAsString(map);
//封装请求实体(请求参数、请求头)
HttpEntity<String> entity = new HttpEntity<>(jsonStr, headers);
//发送请求
Map result = restTemplate.postForObject(expressUrl, entity, Map.class);


//发送携带query参数的uri,使用此api进行编码生成uri
UriComponentsBuilder builder = UriComponentsBuilder
.fromUriString(getUsersUrl)
.queryParam("nameOrEmail", nameOrEmail);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
ResponseEntity<String> exchange = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.PUT, new HttpEntity<>(headers), String.class);


//发送文件
httpHeaders.setAccept(Arrays.asList(MediaType.MULTIPART_FORM_DATA));
httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
//设置请求体,注意是LinkedMultiValueMap
FileSystemResource fileSystemResource = new FileSystemResource(filePath+"/"+fileName);//获取文件资源
MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();//一个key可以存多个value
form.add("file", fileSystemResource);//封装资源文件
form.add("filename",fileName);//封装文件名称
//用HttpEntity封装整个请求报文
HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
String s = restTemplate.postForObject(url, files, String.class);

https请求报错

1
2
3
4
5
6
Exception in thread "main" org.springframework.web.client.ResourceAccessException: I/O error on GET request for "https://ecs.gac.com.cn:3351/ecs-console/api/bill/searchBillCount": sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; nested exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

cn.kjjk.kjpayservice.KjPayServiceApplicationTests.main(KjPayServiceApplicationTests.java:58)
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

处理方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
RestTemplate restTemplate  = new RestTemplate(new HttpsClientRequestFactory());


public class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory {

@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
try {
if (!(connection instanceof HttpsURLConnection)) {// http协议
//throw new RuntimeException("An instance of HttpsURLConnection is expected");
super.prepareConnection(connection, httpMethod);
}
if (connection instanceof HttpsURLConnection) {// https协议,修改协议版本
SSLContext ctx = SSLContext.getInstance("TLSv1.2");
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[]{tm}, null);
org.apache.http.conn.ssl.SSLSocketFactory ssf = new org.apache.http.conn.ssl.SSLSocketFactory(ctx, org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
((HttpsURLConnection) connection).setSSLSocketFactory(ctx.getSocketFactory());
HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;

super.prepareConnection(httpsConnection, httpMethod);
}
} catch (Exception e) {
e.printStackTrace();
}
}