简单记录下RestTemplate使用方法

2023-07-29,,

1.设置get方法

ResponseEntity<JSONObject> responseEntity= restTemplate.getForEntity(url,JSONObject.class);

2.设置post方法

 MultiValueMap map = new LinkedMultiValueMap();
map.add("name", name);
ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, map, JSONObject.class);

3.put方法

  MultiValueMap map = new LinkedMultiValueMap();
map.add("username", "username");
map.add("address", "address");
restTemplate.put(url, map);

4.delete方法

 restTemplate.delete(url, model);

5.配置文件(无配置不可使用)

public class RestConfig {
//不重要
@Bean
public CloseableHttpClient httpClient() throws Exception {
SSLContext context = new SSLContextBuilder().loadTrustMaterial(null, (x509Certificates, s) -> true).build();
SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(context, NoopHostnameVerifier.INSTANCE);
return HttpClients.custom()
.setSSLSocketFactory(factory)
.build();
}
//不重要
@Bean
public ClientHttpRequestFactory httpRequestFactory() throws Exception {
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setHttpClient(httpClient());
factory.setConnectionRequestTimeout(3000);
factory.setReadTimeout(30000);
factory.setConnectTimeout(30000);
return factory;
}
//必须要
@Bean
public RestTemplate restTemplate() throws Exception {
return new RestTemplate(httpRequestFactory());
}
}

简单记录下RestTemplate使用方法的相关教程结束。

《简单记录下RestTemplate使用方法.doc》

下载本文的Word格式文档,以方便收藏与打印。