SpringBoot 使用 RestTemplate 进行 HTTP 请求

1. 简单使用

RestTemplate底层是通过HttpURLConnection实现的。

(1)getForObject

java 复制代码
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

java 复制代码
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

java 复制代码
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

java 复制代码
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

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

(6)exchange

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

java 复制代码
<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;

下面写一个使用例子:

java 复制代码
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. 使用泛型

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

java 复制代码
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);
    }
}
java 复制代码
@Data
public class Result<T> {
    private String logid;
    private T data;
    private Integer status;
    private String message;
    private Double st;
    private Double crt;
}
java 复制代码
@Data
public class Ret {
    private Boolean ret;
    private String photoId;
}
相关推荐
程序媛小果42 分钟前
基于java+SpringBoot+Vue的宠物咖啡馆平台设计与实现
java·vue.js·spring boot
许野平1 小时前
Rust: 利用 chrono 库实现日期和字符串互相转换
开发语言·后端·rust·字符串·转换·日期·chrono
齐 飞3 小时前
MongoDB笔记01-概念与安装
前端·数据库·笔记·后端·mongodb
狂放不羁霸3 小时前
idea | 搭建 SpringBoot 项目之配置 Maven
spring boot·maven·intellij-idea
LunarCod3 小时前
WorkFlow源码剖析——Communicator之TCPServer(中)
后端·workflow·c/c++·网络框架·源码剖析·高性能高并发
成富4 小时前
文本转SQL(Text-to-SQL),场景介绍与 Spring AI 实现
数据库·人工智能·sql·spring·oracle
计算机学长felix4 小时前
基于SpringBoot的“校园交友网站”的设计与实现(源码+数据库+文档+PPT)
数据库·spring boot·毕业设计·交友
码农派大星。4 小时前
Spring Boot 配置文件
java·spring boot·后端
江深竹静,一苇以航4 小时前
springboot3项目整合Mybatis-plus启动项目报错:Invalid bean definition with name ‘xxxMapper‘
java·spring boot
杜杜的man5 小时前
【go从零单排】go中的结构体struct和method
开发语言·后端·golang