一、RestTemplate是什么
RestTemplate是Spring提供的一种简单便捷的模板类来供我们在代码里访问 http
服务,相较于之前常用的HttpClient
,RestTemplate
是一种更为优雅的调用RESTFul
服务的方式。
1.RestTemplate默认是不支持HTTPS请求的
在此有两种解决办法,一是导入证书,二是忽略证书的校验。
忽略证书实例
继承SimpleClientHttpRequestFactory,实现了 ClientHttpRequestFactory
接口,我们需要重写其 prepareConnection()
方法,在此方法里实现对 HttpURLConnection
的重新处理,忽略对证书的校验。创建RestTemplate时使用RestTemplateBuilder来构建,requestFactory()
方法用来设置 ClientHttpRequestFactory
public class HttpsClientHttpRequestFactory extends SimpleClientHttpRequestFactory {
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
try {
if (connection instanceof HttpsURLConnection) {// https协议,修改协议版本
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
// 信任任何链接,忽略对证书的校验
TrustStrategy anyTrustStrategy = (x509Certificates, s) -> true;
//自定义SSLContext
SSLContext ctx = SSLContexts.custom().loadTrustMaterial(trustStore, anyTrustStrategy).build();
// ssl问题
((HttpsURLConnection) connection).setSSLSocketFactory(ctx.getSocketFactory());
//解决No subject alternative names matching IP address xxx.xxx.xxx.xxx found问题
((HttpsURLConnection) connection).setHostnameVerifier((s, sslSession) -> true);
HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
super.prepareConnection(httpsConnection, httpMethod);
} else { // http协议
super.prepareConnection(connection, httpMethod);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
二、创建RestTemplate
1.使用jdk自带的HttpURLConnection作为底层HTTP
客户端实现(默认)
也可以用RestTemplateBuilder
构造类定义一些参数
2.使用Apache的HttpClient作为HTTP
客户端
3.使用OkHttp作为http
客户端
4.注入使用
5.最简单的方式直接在代码里new
三、API使用
1.GET请求
get请求参数传入map时会拼接在url后http://httpbin.org/post?name="彭于晏"
2.POST请求
postForObject();postForEntity()
例子
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String,Object> param = new LinkedMultiValueMap<>();
param.add("tid",tid);
HttpEntity<MultiValueMap<String,Object>> httpEntity = new HttpEntity<>(param,headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> outresponse = restTemplate.postForEntity("url",httpEntity,String.class);
3.PUT请求
put();
使用方法与postForEntity()
参数基本一致,只是put
方法没有返回值
4.DELETE请求
5.EXCHANGE请求
<T> ResponseEntity<T> exchange()
允许用户指定请求的方法(get,post,put
等)