SpringBoot使用RestTemplate发送HTTP请求

使用优雅的发送HTTP请求

以前发送HTTP请求都是基于 HttpClient 的
使用CloseableHttpClient发送HTTP请求
今天看到有人用RestTemplate发送请求,代码特别简单,了解一下。

先了解如何使用,再做说明

使用方式

依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

RestTemplate 本身就像是一个工具类,这里就不再封装了。直接创建对象使用还是创建对象后放到Spring容器里都可以

使用示例
RestTemplate restTemplate = new RestTemplate();
// 发送POST请求
ResponseEntity<Result> response = restTemplate.postForEntity(url, params, Result.class);

方法详解

简介

RestTemplate是Spring用于同步client端的核心类,简化了与http服务的通信,并满足RestFul原则,程序代码可以给它提供URL,并提取结果。默认情况下,RestTemplate默认依赖jdk的HTTP连接工具。当然你也可以 通过setRequestFactory属性切换到不同的HTTP源,比如Apache HttpComponents、Netty和OkHttp。

一、GET方法

在RestTemplate中,对GET请求有两种方式。getForEntitygetForObject

1. getForEntity

getForEntity 方法的返回值是一个ResponseEntity<T>T表示返回值类型,ResponseEntity<T>是 Spring 对 HTTP 请求响应的封装,包括了几个重要的元素,如响应码、contentType、contentLength、响应消息体等。

返回格式
{
    "body":"getForEntity",
    "headers":{
        "Content-Type":[
            "text/plain;charset=UTF-8"
        ],
        "Content-Length":[
            "12"
        ],
        "Date":[
            "Mon, 16 Nov 2020 08:25:48 GMT"
        ]
    },
    "statusCode":"OK",
    "statusCodeValue":200
}
getForEntity共有三个重载
  1. public <T> ResponseEntity<T> getForEntity(URI url, Class<T> responseType)
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/getForEntity";
ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
  1. public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object... uriVariables)
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/getForEntity?param1={param1}&param2={param2}";
ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class, "参数1", "参数2");
  1. public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Map<String, ?> uriVariables)
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/getForEntity?param1={param1}&param2={param2}";
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("param1","参数1");
paramMap.put("param2","参数2");
ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class, paramMap);

2. getForObject

getForObject 函数实际上是对 getForEntity 函数的进一步封装,如果你只关注返回的消息体的内容,对其他信息都不关注,此时可以使用 getForObject

返回格式如同getForEntitybody
getForObject共有三个重载,使用方法同上

二、POST方法

在 RestTemplate 中,POST 请求可以通过如下三个方法来发起:postForEntitypostForObjectpostForLocation

  • postForEntitypostForObject跟上面的get类似,唯一的不同点是参数列表不同,post请求可以发送实体类
    注意:当参数列表中指定实体类时, post 发送的 Content-Typeapplication/json

  • postForLocation:postForLocation 也是提交新资源,提交成功之后,返回新资源的 URI,postForLocation 的参数和前面两种的参数基本一致,只不过该方法的返回值为 URI ,这个只需要服务提供者返回一个 URI 即可,该 URI 表示新资源的位置。


三、使用exchange指定调用方式

方法跟上面的getForObjectgetForEntitypostForObjectpostForEntity 等方法不同之处在于它可以指定请求的HTTP类型;并且可以设置请求头信息

  • public <T> ResponseEntity<T> exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables)
  • public <T> ResponseEntity<T> exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, Class<T> responseType, Map<String, ?> uriVariables)
  • public <T> ResponseEntity<T> exchange(URI url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, Class<T> responseType)

通常用的方法是与上面 GET、POST 的三个重载方法类似的方法,但是 exchange的方法中似乎都有都有@Nullable HttpEntity requestEntity这个参数,可以通过该参数来配置请求体

示例:

String url = "http://localhost:8080/exchange?param1={param1}&param2={param2}";

HttpHeaders headers = new HttpHeaders();
// 请求头添加 loginId、Content-Type、Accept-Charset
headers.set("loginId", "user001");
headers.set("Content-Type", MediaType.TEXT_PLAIN_VALUE);
headers.set("Accept-Charset", "utf-8");

Map<String, Object> paramMap = new HashMap<>();
paramMap.put("param1", "param1");
paramMap.put("param2", "param2");

HttpEntity httpEntity = new HttpEntity(paramMap, headers);

RestTemplate restTemplate = new RestTemplate();
// GET请求
ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
// POST请求
ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
System.out.println(JSONObject.toJSONString(exchange));

更详细的讲解

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值