总结:使用 RestTemplate 发送HTTP请求

1. 背景

一般发送HTTP请求是使用 Apache的HttpClient,它比较灵活。在 spring cloud 中往往提供的 REST 风格的服务。RestTemplate 提供了一种简单便捷的模板类来进行HTTP操作的方式。

或者,根据你的需要可考虑使用org.springframework.web.reactive.client.WebClient 具有更现代API并支持同步,异步和流传输方案。

2.知识

HttpClient 是一个 模板化 的HTTP请求框架,比较适合用调用 REST请求。在 SpringCloud 微服务框架中应用较多。

3. 示例

(1)发送 get 请求

使用getForEntity:发起 get 请求。 无参数的请求方式。

超级简单,见下:

String url = "http://your_url";
ResponseEntity<String> result = restTemplate.getForEntity(url,String.class);

使用getForEntity:发起 get 请求。自己拼接参数字符串方式。

这样的方式要使用 map 传递参数。
如果有汉字要注意需要进行 urlencode。

String url = "http://127.0.0.1:8080/login?name={name}";
Map<String,String> map = new HashMap<>();
map.put("name","join");
ResponseEntity<String> result = restTemplate.getForEntity(url,String.class,map);

使用getForEntity:发起 get 请求。先拼接URI对象传参。

先 使用 UriComponents 构建一个对象,再 expand 替换参数实际的值,这样看起来比较清晰。

  • expand(): 替换参数。
  • encode(): 编码,默认使用utf-8。
UriComponents uriComponents = UriComponentsBuilder
.fromUriString("http://example.com/hotels/{hotel}/bookings/{booking}").build();
URI uri = uriComponents.expand("42", "21").encode().toUri();
ResponseEntity<String> result = restTemplate.getForEntity(uri,String.class);

使用getForEntity:对返回的响应内容转换成实体对象

下面参数要传入一个 class , 这里直接传入 User.class 即可。

String url = "http://127.0.0.1:8080/login?name={name}";
Map<String,String> map = new HashMap<>();
map.put("name","zhang3");
ResponseEntity<User> result = restTemplate.getForEntity(url,User.class,map);

发送带有请求头的get 请求

先构建一个 HttpEntity,构件时传入 header对象,再发送。

String url = "http://127.0.0.1:8080/xxx;
HttpHeaders resultRequestHeader = new HttpHeaders();
resultRequestHeader.add("charset", "UTF-8");
resultRequestHeader.setContentType(MediaType.APPLICATION_JSON);

LinkedMultiValueMap<String, Object> resultParamMap = new LinkedMultiValueMap<>();
 
HttpEntity<String>  resultHttpEntity = new HttpEntity<>(null, resultRequestHeader);
ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET,resultHttpEntity,String.class);

(2)发送 PSOT 请求

使用 postForEntity 发送 post 请求。

和 get 方式类似,使用 postForEntity。

String url = "http://127.0.0.1:8080/login";
LinkedMultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
paramMap.add("username", "zhangsan");
paramMap.add("password", "123456");
paramMap.add("randomStr",String.valueOf(System.currentTimeMillis()));
HttpEntity<LinkedMultiValueMap<String, Object>> httpEntity = new HttpEntity<>(paramMap, requestHeaders);
 
ResponseEntity<String> exchange = restTemplate.postForEntity(url, httpEntity, String.class);
 
String resultRemote = exchange.getBody();//得到返回的值

(3)使用 exchange 方法

exchange 方法:先构建 ResponseEntity ,再发请求

执行给定中指定的请求,RequestEntity并以形式返回响应ResponseEntity。通常采用 builder 链式的方式构建一个 RequestEntity,例如:
方法签名:

public <T> ResponseEntity<T> exchange(RequestEntity<?> entity,
                                      Class<T> responseType)
                               throws RestClientException

示例

MyRequest body = ...
 RequestEntity request = RequestEntity
     .post(new URI("https://example.com/foo"))
     .accept(MediaType.APPLICATION_JSON)
     .body(body);
 ResponseEntity<MyResponse> response = template.exchange(request, MyResponse.class);

exchange 方法:构建 RequestEntity ,发送带有泛型的参数请求

方法签名

public <T> ResponseEntity<T> exchange(RequestEntity<?> entity,
                                      ParameterizedTypeReference<T> responseType)
                               throws RestClientException

见下示例:

MyRequest body = ...
 RequestEntity request = RequestEntity
     .post(new URI("https://example.com/foo"))
     .accept(MediaType.APPLICATION_JSON)
     .body(body);
 ParameterizedTypeReference<List<MyResponse>> myBean =
     new ParameterizedTypeReference<List<MyResponse>>() {};
 ResponseEntity<List<MyResponse>> response = template.exchange(request, myBean);

exchange 方法: 应对泛型集合

对给定的URI模板执行HTTP方法,将给定的请求实体写入请求,并以形式返回响应ResponseEntity。给定ParameterizedTypeReference用于传递 泛型类型 的实体信息:

ParameterizedTypeReference 一般 用于传递 泛型集合 比如 List<MyBean> 这样的。

public <T> ResponseEntity<T> exchange(String url,
                                      HttpMethod method,
                                      @Nullable
                                      HttpEntity<?> requestEntity,
                                      ParameterizedTypeReference<T> responseType,
                                      Object... uriVariables)
                               throws RestClientException

示例:

ParameterizedTypeReference<List<MyBean>> myBean =
     new ParameterizedTypeReference<List<MyBean>>() {};

 ResponseEntity<List<MyBean>> response =
     template.exchange("https://example.com",HttpMethod.GET, null, myBean);

(4)使用 execute 方法

execute 方法请求

对 URI模板 发起 HTTP方法请求,使用 RequestCallback 做请求的处理和准备。并使用 ResponseExtractor 来处理 “响应结果 ”。

签名:

@Nullable
public <T> T execute(String url,
                               HttpMethod method,
                               @Nullable
                               RequestCallback requestCallback,
                               @Nullable
                               ResponseExtractor<T> responseExtractor,
                               Object... uriVariables)
                        throws RestClientException

4.参考:

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
RestTemplate是Spring框架提供的一个用于发送HTTP请求的模板类。通过RestTemplate,我们可以方便地发送GET、POST、PUT、DELETE等不同类型的请求,并获取响应结果。在进行请求转发时,可以使用RestTemplate发送请求到目标后台接口。[1] 要进行请求转发,首先需要引入相关的依赖包,如Apache HttpClient和Spring Boot Web。可以在项目的pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.10</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> ``` 接下来,可以使用RestTemplate发送请求。例如,如果需要将文件上传接口的请求通过RestTemplate转发到另一个后台接口上,可以使用RestTemplate的postForObject方法发送POST请求,并将文件作为参数传递给目标接口。[2] ```java @PostMapping("/xxxx/fileUpload") String fileUpload(@RequestParam(value = "files") MultipartFile[] multipartFiles) { // 使用RestTemplate发送请求转发 RestTemplate restTemplate = new RestTemplate(); String targetUrl = "http://目标后台接口URL"; String response = restTemplate.postForObject(targetUrl, multipartFiles, String.class); return response; } ``` 需要注意的是,根据请求参数的形式,如form-data和raw参数,参数的附加位置可能会有所不同。此外,为了避免出现转码问题,可以先将URL构造为String,然后再创建URI,或直接将URL赋给RestTemplate。[3] 总结起来,使用RestTemplate进行请求转发的步骤包括引入相关依赖、创建RestTemplate实例、构造目标接口的URL,并使用RestTemplate发送请求并获取响应结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值