构造RestTemplate
private RestTemplate restTemplate = new RestTemplate();
public RestTemplate getRestTemplate() {
// 如果中文乱码可以使用此方法修改restTemplate的编码(默认ISO_8859_1)
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("GB2312")));
return restTemplate;
}
// 以下为跳过SSL验证构造的RestTemplate
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version> <!-- 可根据需要使用其他版本 -->
</dependency>
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.converter.StringHttpMessageConverter;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.nio.charset.StandardCharsets;
import java.security.cert.CertificateException;
/**
* 构造RestTemplate
*
* @return
* @throws Exception
*/
public static RestTemplate getRestTemplate() throws Exception {
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
// 超时
factory.setConnectionRequestTimeout(5000);
factory.setConnectTimeout(5000);
factory.setReadTimeout(5000);
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(createIgnoreVerifySSL(),
// 指定TLS版本
null,
// 指定算法
null,
// 取消域名验证
new HostnameVerifier() {
@Override
public boolean verify(String string, SSLSession ssls) {
return true;
}
});
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
factory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(factory);
// 解决中文乱码问题
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
return restTemplate;
}
/**
* 跳过证书效验的sslcontext
*
* @return
* @throws Exception
*/
private static SSLContext createIgnoreVerifySSL() throws Exception {
SSLContext sc = SSLContext.getInstance("TLS");
// 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
X509TrustManager trustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sc.init(null, new TrustManager[] { trustManager }, null);
return sc;
}
POST
// 表单提交方式
HttpHeaders headers = new HttpHeaders();
// 请勿轻易改变此提交方式,大部分的情况下,提交方式都是表单提交
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// 封装参数,千万不要替换为Map与HashMap,否则参数无法传递
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("id", "1");
params.add("name", "test");
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(params, headers);
ResponseEntity<String> responseEntity = getRestTemplate().postForEntity(baseurl + "/user", entity, String.class);
System.out.println(responseEntity.getBody());
// json提交方式
HttpHeaders headers = new HttpHeaders();
headers.add("Token","token");
// 请勿轻易改变此提交方式,大部分的情况下,提交方式都是表单提交
headers.setContentType(MediaType.APPLICATION_JSON);
//设置body参数,并转成json字符串
Map<String,String> param=new HashMap<>();
param.put("id", "123");
String content = JsonUtils.toJsonStr(param);
HttpEntity<String> httpEntity = new HttpEntity<>(content, headers);
String response = restTemplate.postForObject(BASE_URL + "/getCargoAmount", httpEntity, String.class);
System.out.println(response);
GET
方法1
String result = getRestTemplate().getForObject(baseurl + config.getAppId() + "/person/"
+ entity.get("guid")
+ "?appId=" + config.getAppId()
+ "&token=" + token
, String.class);
方法2
// 请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
if(headerList!=null)headerList.forEach(p -> headers.add(p.get("key"), p.get("val")));
// 请求参数
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("sign", "123");
HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(null, headers);
String url = apiHealthCheck.getUrlPath();
if (!params.isEmpty()) {
String queryString = params.entrySet().stream()
.map(it -> it.getValue().stream()
.map(value -> it.getKey() + "=" + value)
.collect(Collectors.joining("&"))
).collect(Collectors.joining("&"));
if (!StringUtils.isEmpty(queryString)) {
url += (url.contains("?") ? "&" : "?") + queryString;
}
}
ResponseEntity<String> responseEntity = getRestTemplate()
.apply(apiHealthCheck.getMaxConnectionSeconds()).exchange(url,
HttpMethod.GET, httpEntity, String.class);
PUT
// 请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// 请求体
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("id","123");
params.add("personGuid", entity.get("personGuid"));// 若为空, 则清空该设备所有的授权记录
HttpEntity<MultiValueMap<String, String>> httpEntity= new HttpEntity<>(params, headers);
ResponseEntity<String> responseEntity = getRestTemplate().exchange(baseurl + config.getAppId() + "/device", HttpMethod.PUT, httpEntity, String.class);
DELETE
// 请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// 请求体
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("id","123");
params.add("personGuid", entity.get("personGuid"));// 若为空, 则清空该设备所有的授权记录
HttpEntity<MultiValueMap<String, String>> httpEntity= new HttpEntity<>(params, headers);
ResponseEntity<String> responseEntity = getRestTemplate().exchange(baseurl + config.getAppId() + "/device", HttpMethod.DELETE, httpEntity, String.class);