SpringBoot使用RestTemplate發(fā)送http請(qǐng)求的實(shí)操演示
1、SpringBoot調(diào)用外部接口的幾種方式
- 原始httpClient
- RestTemplate
- 第三方庫(kù),例如 OKHttp,Hutool等
本文著重介紹RestTemplate方式
2、什么是RestTemplate
RestTemplate是Spring 框架提供的 ,可用于在應(yīng)用中調(diào)用 rest 服務(wù),它簡(jiǎn)化了與 http 服務(wù)的通信方式,統(tǒng)一了 RESTful 的標(biāo)準(zhǔn),封裝了 http 鏈接, 我們只需要傳入url及返回值類型即可。相較于之前常用的 HttpClient,RestTemplate 是一種更優(yōu)雅的調(diào)用 RESTful 服務(wù)的方式。
3、SpringBoot中使用RestTmplate
3.1、前置準(zhǔn)備
1、創(chuàng)建一個(gè)普通的SpringBoot項(xiàng)目
2、創(chuàng)建一個(gè)配置類,
package com.eric.springbootresttemplate.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* @author Eric
* @date 2023-08-03 9:37
*/
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
3、準(zhǔn)備一個(gè)實(shí)體類
package com.eric.springbootresttemplate.entity;
import lombok.Builder;
import lombok.Data;
/**
* @author Eric
* @date 2023-08-03 9:33
*/
@Data
@Builder
public class User {
private Long id;
private String name;
}
4、創(chuàng)建兩個(gè)被請(qǐng)求的接口(模擬其他服務(wù)接口)
@GetMapping("/getUserInfo")
public User getUserList(Long id, String name) {
User user = User.builder().id(id).name(name).build();
return user;
}
@PostMapping("/postUserInfo")
public User postUserInfo(@RequestBody JSONObject jsonObject) {
Long id = jsonObject.getLong("id");
String name = jsonObject.getString("name");
User user = User.builder().id(id).name(name).build();
return user;
}
3.2、Get請(qǐng)求方式
get有兩種請(qǐng)求方式,一種正常的在url拼接參數(shù),一種是使用占位符的方式
方式一:參數(shù)拼接
@Resource
private RestTemplate restTemplate;
/**
* Get請(qǐng)求方式一:參數(shù)拼接
* @param id
* @param name
*/
@GetMapping("/getUserInfoRest")
public void getUserInfoRest(Long id, String name) {
String url = "http://localhost:8080/rest/getUserInfo?id=" + id + "&name=" + name;
ResponseEntity<String> result = restTemplate.getForEntity(url, String.class);
System.out.println(result.getStatusCode());
System.out.println(result.getBody());
System.out.println(result.getHeaders());
}
方式二:占位符方式
直接在方法中指定參數(shù):
@Resource
private RestTemplate restTemplate;
/**
* Get請(qǐng)求方式二:占位符方式
* @param id
* @param name
*/
@GetMapping("/getUserInfoRest2")
public void getUserInfoRest2(Long id, String name) {
String url = "http://localhost:8080/rest/getUserInfo?id={id}&name={name}";
ResponseEntity<String> result = restTemplate.getForEntity(url, String.class,id,name);
System.out.println(result.getStatusCode());
System.out.println(result.getBody());
System.out.println(result.getHeaders());
}
兩種方式的執(zhí)行結(jié)果如下:

3.3、Post請(qǐng)求
/**
* Post請(qǐng)求方式:帶@RequestBody
*/
@PostMapping("/postUserInfoRest")
public void postUserInfoRest() {
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("id", 1L);
requestBody.put("name", "Eric");
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Map<String, Object>> r = new HttpEntity<Map<String, Object>>(requestBody, requestHeaders);
String url = "http://localhost:8080/rest/postUserInfo";
String result = restTemplate.postForObject(url, r, String.class);
System.out.println(result);
}
結(jié)果如下:

3.4、解決中文亂碼
上述請(qǐng)求可能會(huì)存在中文亂碼,只需要額外設(shè)置下即可
RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
3.5、封裝工具類
在日常中,我們可以直接將get和post簡(jiǎn)單的封裝為一個(gè)工具類, 方便我們直接調(diào)用(這里我只是簡(jiǎn)單的封裝了下,大家如果可以根據(jù)自己的使用場(chǎng)景再次封裝~)
package com.wzhy.smart.common.common.utils;
package com.eric.springbootresttemplate.utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
* RestTemplate請(qǐng)求工具類
*
* @author Eric
* @date 2023-08-03 10:36
*/
@Slf4j
public class RestTemplateUtil {
/**
* post請(qǐng)求
*
* @param url 請(qǐng)求路徑
* @param parameter 請(qǐng)求參數(shù)
* @return 返回值
*/
public static String post(String url, Map<String, Object> parameter) {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Map<String, Object>> r = new HttpEntity<Map<String, Object>>(parameter, requestHeaders);
String body = restTemplate.postForObject(url, r, String.class);
// log.info("遠(yuǎn)程調(diào)用結(jié)果,body為:{}", body);
return body;
}
/**
* get請(qǐng)求
*
* @param url 請(qǐng)求路徑
* @param parameter 請(qǐng)求參數(shù)
* @return 返回值
*/
public static String get(String url, Map<String, Object> parameter) {
if (!parameter.isEmpty()) {
url = url + "?";
for (String key : parameter.keySet()) {
url = url + key + "=" + parameter.get(key) + "&";
}
url = url.substring(0, url.length() - 1);
}
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
String body = restTemplate.getForEntity(url, String.class, parameter).getBody();
// log.info("遠(yuǎn)程調(diào)用結(jié)果,body為:{}", body);
return body;
}
}
總結(jié)
到此這篇關(guān)于SpringBoot使用RestTemplate發(fā)送http請(qǐng)求的實(shí)操演示的文章就介紹到這了,更多相關(guān)SpringBoot RestTemplate發(fā)送http請(qǐng)求內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot使用RestTemplate實(shí)現(xiàn)HTTP請(qǐng)求詳解
- springboot中RestTemplate發(fā)送HTTP請(qǐng)求的實(shí)現(xiàn)示例
- springboot中RestTemplate配置HttpClient連接池詳解
- 基于springboot的RestTemplate、okhttp和HttpClient對(duì)比分析
- SpringBoot 利用RestTemplate http測(cè)試
- 關(guān)于springboot 中使用httpclient或RestTemplate做MultipartFile文件跨服務(wù)傳輸?shù)膯?wèn)題
- SpringBoot使用RestTemplate如何通過(guò)http請(qǐng)求將文件下載到本地
相關(guān)文章
詳解RabbitMQ中延遲隊(duì)列結(jié)合業(yè)務(wù)場(chǎng)景的使用
這篇文章主要介紹了詳解RabbitMQ中延遲隊(duì)列結(jié)合業(yè)務(wù)場(chǎng)景的使用,延遲隊(duì)列中的元素都是帶有時(shí)間屬性的,延遲隊(duì)列就是用來(lái)存放需要在指定時(shí)間被處理的元素的隊(duì)列,需要的朋友可以參考下2023-05-05
spring boot配置MySQL數(shù)據(jù)庫(kù)連接、Hikari連接池和Mybatis的簡(jiǎn)單配置方法
這篇文章主要介紹了spring boot配置MySQL數(shù)據(jù)庫(kù)連接、Hikari連接池和Mybatis的簡(jiǎn)單配置方法,需要的朋友可以參考下2018-03-03
mybatis3中@SelectProvider傳遞參數(shù)方式
這篇文章主要介紹了mybatis3中@SelectProvider傳遞參數(shù)方式。具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08
詳談Java中Object類中的方法以及finalize函數(shù)作用
下面小編就為大家?guī)?lái)一篇詳談Java中Object類中的方法以及finalize函數(shù)作用。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-04-04
idea使用pagehelper實(shí)現(xiàn)后端分頁(yè)功能的步驟詳解
這篇文章主要介紹了idea使用pagehelper實(shí)現(xiàn)后端分頁(yè)功能的步驟,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-09-09
Java中的List接口實(shí)現(xiàn)類LinkList和ArrayList詳解
這篇文章主要介紹了Java中的List接口實(shí)現(xiàn)類LinkList和ArrayList詳解,List接口繼承自Collection接口,是單列集合的一個(gè)重要分支,實(shí)現(xiàn)了List接口的對(duì)象稱為L(zhǎng)ist集合,在List集合中允許出現(xiàn)重復(fù)的元素,所有的元素是以一種線性方式進(jìn)行存儲(chǔ)的,需要的朋友可以參考下2024-01-01
RocketMQ設(shè)計(jì)之主從復(fù)制和讀寫分離
這篇文章主要介紹了RocketMQ設(shè)計(jì)之主從復(fù)制和讀寫分離,RocketMQ提高消費(fèi)避免Broker發(fā)生單點(diǎn)故障引起B(yǎng)roker上的消息無(wú)法及時(shí)消費(fèi),下文關(guān)于了RocketMQ的相關(guān)內(nèi)容,需要的小伙伴可以參考一下2022-03-03
Spring Boot核心注解@ResponseBody深度解析與實(shí)戰(zhàn)指南
SpringBoot中@ResponseBody注解詳解,全面拆解其核心作用、工作原理、實(shí)戰(zhàn)示例、簡(jiǎn)化用法及注意事項(xiàng),本文介紹Spring Boot核心注解@ResponseBody深度解析與實(shí)戰(zhàn)指南,感興趣的朋友跟隨小編一起看看吧2026-01-01

