SpringBoot使用RestTemplate实现HTTP请求详解

 更新时间:2024年03月21日 08:21:49   作者:一线大码  
这篇文章主要为大家详细介绍了SpringBoot如何使用RestTemplate实现进行HTTP请求,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下

1. 简单使用

RestTemplate底层是通过HttpURLConnection实现的。

(1)getForObject

RestTemplate restTemplate = new RestTemplate(https://blog.csdn.net/mryang125/article/details/80955558);
String url = "http://localhost:8080/user/{id}";
UserVo userVo = restTemplate.getForObject(url, UserVo.class, id);

第一个参数表示URL,第二个参数表示返回类型,第三个参数表示URI中对应的参数,是一个可变长参数,可按顺序写多个参数。

(2)getForEntity

RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/users/{userName}/{note}/{start}/{limit}";
//使用map封装多个参数
Map<String, Object> params = new HashMap<>();
params.put("userName", userName);
params.put("note", note);
params.put("start", start);
params.put("limit", limit);
ResponseEntity<List> responseEntity = restTemplate.getForEntity(url, List.class, params);
List<UserVo> userVos = responseEntity.getBody();

(3)postForObject

RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/user";
//设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
//创建请求实体对象
HttpEntity<UserVo> request = new HttpEntity<>(newUserVo, headers);
User user = restTemplate.postForObject(url, request, User.class);

(4)postForEntity

RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/user";
//设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
//创建请求实体对象
HttpEntity<UserVo> request = new HttpEntity<>(newUserVo, headers);
//请求服务器
ResponseEntity<User> responseEntity = restTemplate.postForEntity(url, request, User.class);
//获取响应体
User user = responseEntity.getBody();
//获取响应头
HttpHeaders respHeaders = responseEntity.getHeaders();
//获取响应属性
List<String> success = respHeaders.get("success");
//获取响应状态码
int statusCode = responseEntity.getStatusCodeValue();

(5)delete

RestTemplate restTemplate = new RestTemplate();
restTemplate.delete("http://localhost:8080/use/{id}", id);

(6)exchange

RestTemplate还提供了一个exchange方法,该方法比上面的方法灵活,可以通过制定参数实现各种Http请求。下面列出Spring提供的八种方法。

<T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables) throws RestClientException;

<T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException;

<T> ResponseEntity<T> exchange(URI url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType) throws RestClientException;

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

<T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType, Map<String, ?> uriVariables) throws RestClientException;

<T> ResponseEntity<T> exchange(URI url, HttpMethod method, HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType) throws RestClientException;

<T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity, Class<T> responseType) throws RestClientException;

<T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity, ParameterizedTypeReference<T> responseType) throws RestClientException;

下面写一个使用例子:

RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/user";
//设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
//创建请求实体对象
HttpEntity<UserVo> request = new HttpEntity<>(newUserVo, headers);
//请求服务器
ResponseEntity<User> responseEntity = restTemplate.exchange(url,  HttpMethod.POST, request, User.class);
//获取响应体
User user = responseEntity.getBody();
//获取响应头
HttpHeaders respHeaders = responseEntity.getHeaders();
//获取响应属性
List<String> success = respHeaders.get("success");
//获取响应状态码
int statusCode = responseEntity.getStatusCodeValue();

//获取资源
String url1 = "http://localhost:8080/user/{id}";
ResponseEntity<User> responseEntity1 = restTemplate.exchange(url1,  HttpMethod.GET, null, User.class, id);
//获取响应体
User user1 = responseEntity1.getBody();

2. 使用泛型

使用泛型接收响应,这里添加一个返回类型中泛型的使用方法:

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

//创建请求实体对象,这里将参数转换为JSON字符串了
HttpEntity<String> request = new HttpEntity<>(paramJsonStr, headers);
//请求服务器
RestTemplate restTemplate = new RestTemplate();
String url = "http://www.baidu.com/task";
ResponseEntity<String> responseEntity = null;
try {
	//统一使用String接收响应,再用Jackson转为对应的实体类
    responseEntity = restTemplate.postForEntity(url, request, String.class);
//这里使用try...catch是因为有可能因为网络原因出现错误,RestClientException 的子类 ResourceAccessException 异常
} catch (RestClientException e) {
    e.printStackTrace();
}

if (responseEntity != null) {
    //获取响应体
    String body = responseEntity.getBody();
    //使用Jackson转为对应的实体类,这里的Result中使用到了泛型,用来应对多种格式
    ObjectMapper mapper = new ObjectMapper();
    Result<Ret> result = mapper.readValue(body, new TypeReference<Result<Ret>>() {});
    if (result != null) {
    	//使用了泛型,不同的请求这里就可以获取到不同类型的data
        Ret data = result.getData();
        System.out.println("data : " + data);
    }
}
@Data
public class Result<T> {
    private String logid;
    private T data;
    private Integer status;
    private String message;
    private Double st;
    private Double crt;
}
@Data
public class Ret {
    private Boolean ret;
    private String photoId;
}

以上就是SpringBoot使用RestTemplate实现HTTP请求详解的详细内容,更多关于SpringBoot RestTemplate实现HTTP请求的资料请关注脚本之家其它相关文章!

相关文章

  • Spring Boot 全局异常处理策略设计之@ExceptionHandler 与 @ControllerAdvice 生效原理源码解析

    Spring Boot 全局异常处理策略设计之@ExceptionHandler 与&nb

    SpringBoot全局异常处理策略设计@ExceptionHandler与@ControllerAdvice生效原理源码解析,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2026-01-01
  • SpringBoot使用CXF集成WebService的方法

    SpringBoot使用CXF集成WebService的方法

    这篇文章主要介绍了SpringBoot使用CXF集成WebService的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-08-08
  • SpringBoot详解整合Redis缓存方法

    SpringBoot详解整合Redis缓存方法

    本文主要介绍了SpringBoot整合Redis缓存的实现方法,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-07-07
  • Java返回分页结果集的封装代码实例

    Java返回分页结果集的封装代码实例

    这篇文章主要介绍了java返回分页结果集的封装代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-01-01
  • 关于Java中的可见性和有序性问题

    关于Java中的可见性和有序性问题

    这篇文章主要介绍了关于Java中的可见性和有序性问题,Java在诞生之初就支持多线程,自然也有针对这三者的技术方案,今天就学习一下Java如何解决其中的可见性和有序性导致的问题,需要的朋友可以参考下
    2023-08-08
  • java用LocalDateTime类获取当天时间、前一天时间及本周/本月的开始和结束时间

    java用LocalDateTime类获取当天时间、前一天时间及本周/本月的开始和结束时间

    这篇文章主要给大家介绍了关于java使用LocalDateTime类获取当天时间、前一天时间及本周/本月的开始和结束时间的相关资料,文中通过代码示例介绍的非常详细,需要的朋友可以参考下
    2023-08-08
  • Java冒泡排序的定义与实例代码

    Java冒泡排序的定义与实例代码

    这篇文章主要给大家介绍了关于Java冒泡排序的定义与实例的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-12-12
  • 代码分析Spring MVC的工作原理

    代码分析Spring MVC的工作原理

    在本篇文章里小编给大家整理了关于Spring MVC的工作原理的相关知识点以及实例代码内容,需要的朋友们可以参考下。
    2019-06-06
  • Maven发布项目 (jar包) 到Nexus私服中的操作

    Maven发布项目 (jar包) 到Nexus私服中的操作

    这篇文章主要介绍了Maven发布项目 (jar包) 到Nexus私服中的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-10-10
  • Spring中的Lifecycle接口使用与源码分析

    Spring中的Lifecycle接口使用与源码分析

    这篇文章主要介绍了Spring中的Lifecycle接口使用与源码分析,LifeCycle接口定义了Spring容器的生命周期,任何被Spring管理的对象都可以实现该接口,需要的朋友可以参考下
    2023-05-05

最新评论