【spring boot】 使用 RestTemplate

时间:2025-03-01 21:38:10

这里写目录标题

  • 前言
  • 准备
    • 引入 lib
    • 创建 RestTemplate Bean
  • 认识一下RestTemplate
  • getForObject 示例
    • 简单调用
    • 参数拼接
  • postForEntity 示例
    • 构造 request Object
    • 在 URL 中传参
  • postForObject 示例
    • 构造 request Object
    • 在 URL 中传参
  • (POST)Content-Type: application/x-www-form-urlencoded
  • (POST)Content-Type: application/json
  • (POST)Content-Type: application/json
  • postForEntity 与 postForObject 的区别
  • exchange 示例
    • 简单的GET调用
    • 简单的POST调用
    • 参数拼接
    • 添加Header
    • 添加Body

前言

  • spring-boot 2.0.
  • spring-web 5.0.
  • maven 3.5.0
  • Eclipse Version: 2019-09 R (4.13.0)
  • 使用 RestTemplate 调用 restful 接口
  • 官方说明在这里这里

准备

引入 lib

RestTemplate 类的完整路径为 : 。
RestTemplate 类在 lib : spring-web 中。

springboot项目引入 lib:

<dependency>
	<groupId></groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

创建 RestTemplate Bean

@Configuration
public class RestTemplateConfig {
	@Bean
	public RestTemplate getRestTemplate() {
		return new RestTemplate();
	}
}

说明:

  • 也可以不创建Bean。不创建Bean时,需要每次new RestTemplate()
  • 如果既不创建Bean,也不每次new RestTemplate(),则会遇到错误No qualifying bean of type ''

认识一下RestTemplate

常用方法,getForEntitygetForObject方法、postForEntitypostForObject方法。ForEntity方法和ForObject方法的差别在于返回值。ResponseEntity类型的返回值可以获取到完整的Response信息,比如header、http status。部分相关方法定义:

  • public <T> ResponseEntity<T> getForEntity(URI url, Class<T> responseType) throws RestClientException
  • public <T> T getForObject(URI url, Class<T> responseType) throws RestClientException
  • public <T> ResponseEntity<T> postForEntity(URI url, @Nullable Object request, Class<T> responseType) throws RestClientException
  • public <T> T postForObject(URI url, @Nullable Object request, Class<T> responseType) throws RestClientException

exchange方法更偏向于自己处理RequestEntity的情况。

getForObject 示例

简单调用

String url = "/s?q=abc";
// 将url返回的内容,存入变量result中
String result = this.restTemplate.getForObject(url, String.class);

参数拼接

String url = "/s?q={keyword}";
Map<String, String> paramMap = new HashMap<>();
paramMap.put("keyword", "abc");
// 将url返回的内容,存入变量result中
String result = this.restTemplate.getForObject(url, String.class, paramMap);

postForEntity 示例

构造 request Object

@Service
public class DataSendService {
	@Autowired
	private RestTemplate restTemplate;

	public void sendData() {
		String url = "http://localhost:8080/app/data-accept";
		
		HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> paramMap= new LinkedMultiValueMap<>();
        paramMap.add("name", "zhangsan");
        
        HttpEntity<MultiValueMap<String, String>> entity = null;
        entity = new HttpEntity<>(paramMap, headers);
        
        ResponseEntity<String> exchange = this.restTemplate.postForEntity(url, 
        									entity, String.class);
        String result = exchange.getBody();
        System.out.println(result);
	}
}

在 URL 中传参

@Service
public class DataSendService {
	@Autowired
	private RestTemplate restTemplate;

	public void sendData() {
		String url = "http://localhost:8080/app/data-accept?name={name}";
        ResponseEntity<String> exchange = this.restTemplate.postForEntity(url, 
        									null, String.class, "zhangsan");
        System.out.println(exchange.getBody());
	}
}

postForObject 示例

构造 request Object

@Service
public class DataSendService {
	@Autowired
	private RestTemplate restTemplate;

	public void sendData() {
		String url = "http://localhost:8080/app/data-accept";
		
		HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> paramMap= new LinkedMultiValueMap<>();
        paramMap.add("name", "zhangsan");
        
        HttpEntity<MultiValueMap<String, String>> entity = null;
        entity = new HttpEntity<>(paramMap, headers);
        
        String result = this.restTemplate.postForObject(url, 
        									entity, String.class);
        System.out.println(result);
	}
}

在 URL 中传参

@Service
public class DataSendService {
	@Autowired
	private RestTemplate restTemplate;

	public void sendData() {
		String url = "http://localhost:8080/app/data-accept?name={name}";
        String result = this.restTemplate.postForObject(url, 
        									null, String.class, "zhangsan");
        System.out.println(result);
	}
}

(POST)Content-Type: application/x-www-form-urlencoded

@Service
public class DataSendService {
	@Autowired
	private RestTemplate restTemplate;

	public void sendData() {
		String url = "http://localhost:8080/app/data-accept";
		
		HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> paramMap= new LinkedMultiValueMap<>();
        paramMap.add("name", "zhangsan");
        
        HttpEntity<MultiValueMap<String, String>> entity = null;
        entity = new HttpEntity<>(paramMap, headers);
        
        String result = this.restTemplate.postForObject(url, 
        									entity, String.class);
        System.out.println(result);
	}
}

(POST)Content-Type: application/json

@Service
public class DataSendService {
	@Autowired
	private RestTemplate restTemplate;

	public void sendData() {
		String url = "http://localhost:8080/app/data-accept";
		
		HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("name", "zhangsan");
		jsonBody.put("age", 18);
        
        HttpEntity<JSONObject> entity = null;
        entity = new HttpEntity<>(jsonBody , headers);
        
        String result = this.restTemplate.postForObject(url, 
        									entity, String.class);
        System.out.println(result);
	}
}

(POST)Content-Type: application/json

@Service
public class DataSendService {
	@Autowired
	private RestTemplate restTemplate;

	public void sendData() {
		String url = "http://localhost:8080/app/data-accept";
		
		HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_PLAIN);
        String message = "this is a text";
        
        HttpEntity<String > entity = null;
        entity = new HttpEntity<>(message , headers);
        
        String result = this.restTemplate.postForObject(url, 
        									entity, String.class);
        System.out.println(result);
	}
}

postForEntity 与 postForObject 的区别

参数一样,功能一样,返回值类型不一样。

public <T> T postForObject(String url, @Nullable Object request, Class<T> responseType,
		Object... uriVariables) throws RestClientException {
	...
}
public <T> T postForObject(String url, @Nullable Object request, Class<T> responseType,
		Map<String, ?> uriVariables) throws RestClientException {
	...
}
public <T> T postForObject(URI url, @Nullable Object request, Class<T> responseType)
		throws RestClientException {
	...
}
public <T> ResponseEntity<T> postForEntity(String url, @Nullable Object request,
		Class<T> responseType, Object... uriVariables) throws RestClientException {
	...
}
public <T> ResponseEntity<T> postForEntity(String url, @Nullable Object request,
		Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException {
	...
}
@Override
public <T> ResponseEntity<T> postForEntity(URI url, @Nullable Object request, Class<T> responseType)
		throws RestClientException {
	...
}

exchange 示例

简单的GET调用

String url = "/s?q=abc";
// 将url返回的内容,存入变量result中
ResponseEntity<String> exchange = this.restTemplate.exchange(url, HttpMethod.GET, null, String.class);
String result = exchange.getBody();

与下面的效果一致

String url = "/s?q=abc";
// 将url返回的内容,存入变量result中
String result = this.restTemplate.getForObject(url, String.class);

简单的POST调用

String url = "/s?q=abc";
// 将url返回的内容,存入变量result中
ResponseEntity<String> exchange = this.restTemplate.exchange(url, HttpMethod.POST, null, String.class);
String result = exchange.getBody();

参数拼接

String url = "/s?q={keyword}";
Map<String, String> paramMap = new HashMap<>();
paramMap.put("keyword", "abc");
// 将url返回的内容,存入变量result中
ResponseEntity<String> exchange = this.restTemplate.exchange(url, HttpMethod.GET, null, String.class, paramMap);
String result = exchange.getBody();

添加Header

String url = "/s?q={keyword}";
Map<String, String> paramMap = new HashMap<>();
paramMap.put("keyword", "abc");

HttpHeaders headers = new HttpHeaders();
headers.add("access-token", "tk.ssski23rruwerjfqejfxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(null, headers);
  
// 将url返回的内容,存入变量result中
ResponseEntity<String> exchange = this.restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class, paramMap);
String result = exchange.getBody();

添加Body

注意,添加Body时,须为POST请求。

String url = "/s?q={keyword}";
Map<String, String> paramMap = new HashMap<>();
paramMap.put("keyword", "abc");

HttpHeaders headers = new HttpHeaders();
headers.add("access-token", "tk.ssski23rruwerjfqejfxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> bodyMap = new LinkedMultiValueMap<>();
bodyMap.add("client_key", "23xxxxxxxxxxxxxx");
bodyMap.add("client_secret", "rtexxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
bodyMap.add("grant_type", "client_credential");
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(bodyMap, headers);

// 将url返回的内容,存入变量result中
ResponseEntity<String> exchange = this.restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class, paramMap);
String result = exchange.getBody();