SpringBoot使用RestTemplate發(fā)送http請求的實操演示
1、SpringBoot調(diào)用外部接口的幾種方式
- 原始httpClient
- RestTemplate
- 第三方庫,例如 OKHttp,Hutool等
本文著重介紹RestTemplate方式
2、什么是RestTemplate
RestTemplate是Spring 框架提供的 ,可用于在應(yīng)用中調(diào)用 rest 服務(wù),它簡化了與 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)建一個普通的SpringBoot項目
2、創(chuàng)建一個配置類,
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)備一個實體類
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)建兩個被請求的接口(模擬其他服務(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請求方式
get有兩種請求方式,一種正常的在url拼接參數(shù),一種是使用占位符的方式
方式一:參數(shù)拼接
@Resource private RestTemplate restTemplate; /** * Get請求方式一:參數(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請求方式二:占位符方式 * @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請求
/** * Post請求方式:帶@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、解決中文亂碼
上述請求可能會存在中文亂碼,只需要額外設(shè)置下即可
RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
3.5、封裝工具類
在日常中,我們可以直接將get和post簡單的封裝為一個工具類, 方便我們直接調(diào)用(這里我只是簡單的封裝了下,大家如果可以根據(jù)自己的使用場景再次封裝~)
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請求工具類 * * @author Eric * @date 2023-08-03 10:36 */ @Slf4j public class RestTemplateUtil { /** * post請求 * * @param url 請求路徑 * @param parameter 請求參數(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("遠程調(diào)用結(jié)果,body為:{}", body); return body; } /** * get請求 * * @param url 請求路徑 * @param parameter 請求參數(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("遠程調(diào)用結(jié)果,body為:{}", body); return body; } }
總結(jié)
到此這篇關(guān)于SpringBoot使用RestTemplate發(fā)送http請求的實操演示的文章就介紹到這了,更多相關(guān)SpringBoot RestTemplate發(fā)送http請求內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot使用RestTemplate實現(xiàn)HTTP請求詳解
- springboot中RestTemplate發(fā)送HTTP請求的實現(xiàn)示例
- springboot中RestTemplate配置HttpClient連接池詳解
- 基于springboot的RestTemplate、okhttp和HttpClient對比分析
- SpringBoot 利用RestTemplate http測試
- 關(guān)于springboot 中使用httpclient或RestTemplate做MultipartFile文件跨服務(wù)傳輸?shù)膯栴}
- SpringBoot使用RestTemplate如何通過http請求將文件下載到本地
相關(guān)文章
Java利用MessageFormat實現(xiàn)短信模板的匹配
這篇文章主要介紹了Java利用MessageFormat實現(xiàn)短信模板的匹配,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-06-06spring使用validation參數(shù)及全局異常檢測方式
本文主要介紹了Java的數(shù)據(jù)校驗規(guī)范validation-api,包括其定義的注解和HibernateValidator的實現(xiàn),還介紹了spring-boot-starter-validation的使用,可以讓開發(fā)者在SpringBoot應(yīng)用中簡化數(shù)據(jù)校驗的功能2025-02-02SpringBoot中@RestControllerAdvice注解的使用
這篇文章主要介紹了SpringBoot中@RestControllerAdvice注解的使用,@RestControllerAdvice主要用精簡客戶端返回異常,它可以捕獲各種異常,需要的朋友可以參考下2024-01-01Servlet關(guān)于RequestDispatcher的原理詳解
這篇文章主要介紹了Servlet關(guān)于RequestDispatcher的原理詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11