可能是最优雅的http客户端
注意,我测试的接口返回类型全部是String 类型,所以ResponseType 全部是String.class,所以请根据实际情况,酌情修改!
1 不带参数的GET请求
// 方式1: 返回是一个response 对象
ResponseEntity<String> forEntity = restTemplate.getForEntity("http://127.0.0.1:1234/test1", String.class);
System.out.println("1-getForEntry--->" + forEntity.getStatusCode() + forEntity.getBody());
// 方式2: 返回是一个POJO
String forObject = restTemplate.getForObject("http://localhost:1234/test1", String.class);
System.out.println("1-getForObject--->" + forObject.toString());
2 带参数的GET请求方式PathAverable
/**
*@ desc : 带参数的GET请求 PathVarable
*/
// 方式1: 返回是一个response 对象
ResponseEntity<String> forEntity2 = restTemplate.getForEntity("http://localhost:1234/test2/{1}/{2}", String.class, 1, 2);
System.out.println("2-getForObject--->" + forEntity2.getStatusCode() + forEntity2.getBody().toString());
// 方式2: 返回是一个POJO
String forObject2 = restTemplate.getForObject("http://localhost:1234/test2/{1}/{2}", String.class, 1, 2);
System.out.println("2-getForEntry--->" + forObject2.toString());
<!-- 或者 用map 装参数-->
/**
*@ desc : 带参数的GET请求 PathVarable 方式2 map
*/
// 方式1: 返回是一个response 对象
HashMap<String, Object> map = new HashMap<>();
map.put("param", "1");
map.put("param2", "2");
ResponseEntity<String> forEntity2_1 = restTemplate.getForEntity("http://localhost:1234/test2/{param}/{param2}", String.class, map);
System.out.println("2-1-getForObject--->" + forEntity2_1.getStatusCode() + forEntity2_1.getBody());
// 方式2: 返回是一个POJO
String forObject2_2 = restTemplate.getForObject("http://localhost:1234/test2/{param}/{param2}", String.class, map);
System.out.println("2-2-getForEntry--->" + forObject2_2);
3 带参数的GET请求 RequestParam
你需要一个拼接url的工具类方法,不过不要紧,我已经给你写好了
/**
* @ desc : 把参参数 用 xxx=xxx&xxx=xxx 形式
*/
private static String paramToUrl(String url, HashMap<String, Object> map) {
String s = map.entrySet().parallelStream().map(
m -> m.getKey() + "=" + m.getValue()
).collect(Collectors.joining("&"));
return url + "?" + s;
}
然后
/**
*@ desc : 带参数的GET请求 RequestParam
*/
HashMap<String, Object> map2 = new HashMap<>();
map2.put("param", "1");
map2.put("param2", "2");
// 方式1: 返回是一个response 对象
ResponseEntity<String> forEntity3 = restTemplate.getForEntity(paramToUrl("http://localhost:1234/test3", map2), String.class);
System.out.println("3-getForObject--->" + forEntity3.getStatusCode() + forEntity3.getBody().toString());
// 方式2: 返回是一个POJO
String forObject3 = restTemplate.getForObject(paramToUrl("http://localhost:1234/test3", map2), String.class);
System.out.println("3-getForEntry--->" + forObject3.toString());
4 POST 请求
post 请求的body 使用了HttpEntity,httpEntity 包含header 和body,如下
RestTemplate restTemplate = new RestTemplate();
JSONObject body = new JSONObject();
body.put("name", "ligen");
body.put("age", 20);
body.put("hobit", "game");
HttpEntity<Object> entry = new HttpEntity<>(body);
// 方式1: 返回是一个response 对象
ResponseEntity<String> forEntity4 = restTemplate.postForEntity("http://localhost:1234/test4", entry, String.class);
System.out.println("4-postForObject--->" + forEntity4.getStatusCode() + forEntity4.getBody());
// 方式2: 返回是一个POJO
String forObject4 = restTemplate.postForObject("http://localhost:1234/test4", entry, String.class);
System.out.println("4-postForEntry--->" + forObject4);
5 GET 怎么添加Header
上面的示例中,只有Post 参数的传递使用了HttpEntity,在HttpEntity 中我们可以快乐的定义自己的header和body,那么在GET请求中,我们需要添加Header,改怎么添加呢? 经常会有这样的场景,需要在请求头上添加token。。。不好意思,GET 不能直接添加Header。。这种情况下,你就需要使用exchange 方法。
exchange 方法是全能的,因为它允许我们在参数上指定请求方式,并且参数用的是HttpEntity。 那么它当然可以应付上面任何一种情况。真香!!!
如下
RestTemplate restTemplate = new RestTemplate();
// 设置Header
HttpHeaders head = new HttpHeaders();
head.add("token", "aaaaaaaaa");
// 设置请求 如果是Get body 可以设置为null, 如果是POST 直接设置body
HttpEntity<Object> entity = new HttpEntity<>(null, head);
// 发送请求
ResponseEntity<String> exchange = restTemplate.exchange("http://localhost:1234/test1/{1}/{2}", HttpMethod.GET, entity, String.class,1,2);
6 配置SSL,发送https请求, 或者配置客户端证书,实现双向认证
网上配置ssl的方式有很多,找到一种简单的,经过验证确实可用,如下
1 添加依赖
<!-- 配置restTemplate 的ssl有用到 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
<scope>compile</scope>
</dependency>
2 添加一个配置类
@Configuration
public class SSLConfig {
// 证书密码
String password = "123456";
@Bean
public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException, IOException, CertificateException {
SSLContext sslContext = new SSLContextBuilder()
// 配置客户端证书,双向认真,password 为证书密码
// .loadTrustMaterial(ResourceUtils.getFile("classpath:truststore.jks"), password.toCharArray(), (TrustStrategy) (arg0, arg1) -> true)
// 不配置客户端证书,仅单向认证
.loadTrustMaterial(null, (arg0, arg1) -> true)
.build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext,
new String[]{"TLSv1"},
null,
NoopHostnameVerifier.INSTANCE);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(csf)
.build();
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
return restTemplate;
}
}
然后在需要用到 restTemplate的时候,直接使用@Autowire这个Bean,然后进行请求即可

本文详细介绍如何使用RestTemplate优雅地执行HTTP请求,包括GET和POST请求的多种方式,以及如何添加Header和配置SSL进行HTTPS请求。文章还提供了实用的代码示例。
4987

被折叠的 条评论
为什么被折叠?



