SpringBoot RestTemplate GET POST請(qǐng)求的實(shí)例講解
一)RestTemplate簡(jiǎn)介
RestTemplate是HTTP客戶(hù)端庫(kù)提供了一個(gè)更高水平的API。主要用于Rest服務(wù)調(diào)用。
RestTemplate方法:
| 方法組 | 描述 |
|---|---|
|
getForObject |
通過(guò)GET檢索表示形式。 |
|
getForEntity |
ResponseEntity通過(guò)使用GET 檢索(即狀態(tài),標(biāo)頭和正文)。 |
|
headForHeaders |
通過(guò)使用HEAD檢索資源的所有標(biāo)頭。 |
|
postForLocation |
通過(guò)使用POST創(chuàng)建新資源,并Location從響應(yīng)中返回標(biāo)頭。 |
|
postForObject |
通過(guò)使用POST創(chuàng)建新資源,并從響應(yīng)中返回表示形式。 |
|
postForEntity |
通過(guò)使用POST創(chuàng)建新資源,并從響應(yīng)中返回表示形式。 |
|
put |
通過(guò)使用PUT創(chuàng)建或更新資源。 |
|
patchForObject |
通過(guò)使用PATCH更新資源,并從響應(yīng)中返回表示形式。請(qǐng)注意,JDK HttpURLConnection不支持PATCH,但是Apache HttpComponents和其他支持。 |
|
delete |
使用DELETE刪除指定URI處的資源。 |
|
optionsForAllow |
通過(guò)使用ALLOW檢索資源的允許的HTTP方法。 |
|
exchange |
前述方法的通用性強(qiáng)(且意見(jiàn)少的版本),在需要時(shí)提供了額外的靈活性。它接受RequestEntity(包括HTTP方法,URL,標(biāo)頭和正文作為輸入)并返回ResponseEntity。 這些方法允許使用ParameterizedTypeReference而不是Class使用泛型來(lái)指定響應(yīng)類(lèi)型。 |
|
execute |
執(zhí)行請(qǐng)求的最通用方法,完全控制通過(guò)回調(diào)接口進(jìn)行的請(qǐng)求準(zhǔn)備和響應(yīng)提取。 |
二)RestTemplate案例
第一步:創(chuàng)建一個(gè)maven項(xiàng)目,在pom.xml引入一個(gè)springboot的版本
pom.xml內(nèi)容:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.oysept</groupId>
<artifactId>spring_resttemplate</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.oysept.RestTemplateApplication</mainClass>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml配置:該配置就一個(gè)默認(rèn)端口
server:
port: 8080
創(chuàng)建一個(gè)springboot啟動(dòng)類(lèi)RestTemplateApplication
package com.oysept;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
@SpringBootApplication
public class RestTemplateApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(RestTemplateApplication.class).run(args);
}
}
到此步驟時(shí),可以先運(yùn)行RestTemplateApplication中的main方法,檢驗(yàn)springboot啟動(dòng)是否正常。
第二步:創(chuàng)建一個(gè)RestTemplate配置類(lèi)并注入,因?yàn)樵谑褂脮r(shí),不提前注入ResttTemplate,在通過(guò)@Autowired使用會(huì)報(bào)RestTemplate找不到
package com.oysept.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* 注冊(cè)一個(gè)RestTemplate Bean, 否則直接通過(guò)@Autowired使用會(huì)報(bào)RestTemplate找不到
* @author ouyangjun
*/
@Configuration
public class RestTemplateConfig {
/**
* 方式一: 默認(rèn)是使用JDK原生java.net.HttpURLConnection請(qǐng)求
* @return
*/
@Bean(name = "restTemplate")
public RestTemplate restTemplate() {
return new RestTemplate();
}
/**
* 方式二: 使用apache http內(nèi)置請(qǐng)求, 需要在pom.xml中引入相應(yīng)的apache jar
* 可以使用HttpClient,設(shè)置一些http連接池等信息
* @return
*
@Bean(name = "restTemplate")
public RestTemplate restTemplate() {
return new RestTemplate(new HttpComponentsClientHttpRequestFactory());
}
*/
/**
* 方式三: 使用OkHttp內(nèi)置請(qǐng)求, 需要在pom.xml中引入相應(yīng)的OkHttp3 jar
* 可以使用OkHttpClient,設(shè)置一些http連接池信息
* @return
*
@Bean(name = "restTemplate")
public RestTemplate restTemplate() {
return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
}
*/
}
第三步:創(chuàng)建一個(gè)VO類(lèi),用于測(cè)試入?yún)⒑统鰠?/p>
package com.oysept.vo;
public class MsgVO {
private String msgKey;
private String msgValue;
public String getMsgKey() {return msgKey;}
public void setMsgKey(String msgKey) {this.msgKey = msgKey;}
public String getMsgValue() {return msgValue;}
public void setMsgValue(String msgValue) {this.msgValue = msgValue;}
public String toString() {
return "MsgVO [msgKey: "+this.msgKey+", msgValue: "+this.msgValue+"]";
}
}
第四步:創(chuàng)建一個(gè)服務(wù)端接口,用于測(cè)試
package com.oysept.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.oysept.vo.MsgVO;
/**
* 服務(wù)端, 提供接口被調(diào)用
* @author ouyangjun
*/
@RestController
public class ServerController {
// 無(wú)參GET請(qǐng)求: http://localhost:8080/server/get
@RequestMapping(value = "/server/get", method = RequestMethod.GET)
public String get() {
return "/server/get";
}
// 帶參GET請(qǐng)求: http://localhost:8080/server/get/param?param=111222333444
@RequestMapping(value = "/server/get/param", method = RequestMethod.GET)
public String getParam(@RequestParam(value = "param") String param) {
return "/server/get/param," + param;
}
// 路徑中帶參GET請(qǐng)求: http://localhost:8080/server/get/url/AAAA/BBBB
@RequestMapping(value = "/server/get/url/{one}/{two}", method = RequestMethod.GET)
public String getUrl(@PathVariable("one") String one, @PathVariable("two") String two) {
return "/get/url/{one}/{two}," + one + "," + two;
}
// 無(wú)參GET請(qǐng)求, 返回List: http://localhost:8080/server/get/list
@RequestMapping(value = "/server/get/list", method = RequestMethod.GET)
public List<Object> getList() {
List<Object> list = new ArrayList<Object>();
list.add(11);
list.add("AA");
return list;
}
// 無(wú)參GET請(qǐng)求, 返回對(duì)象: http://localhost:8080/server/get/MsgVO
@RequestMapping(value = "/server/get/MsgVO", method = RequestMethod.GET)
public MsgVO getMsgVO() {
MsgVO vo = new MsgVO();
vo.setMsgKey("keyAAA");
vo.setMsgValue("valueBBB");
return vo;
}
// POST請(qǐng)求, 表單參數(shù), application/x-www-form-urlencoded
@RequestMapping(value = "/server/post/form", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public MsgVO postForm(MsgVO msgVO) {
System.out.println("msgKey: " + msgVO.getMsgKey() + ", msgValue: " + msgVO.getMsgValue());
return msgVO;
}
// POST請(qǐng)求, JSON參數(shù), application/json
@RequestMapping(value = "/server/post/json", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public MsgVO postJson(@RequestBody MsgVO msgVO) {
System.out.println("msgKey: " + msgVO.getMsgKey() + ", msgValue: " + msgVO.getMsgValue());
return msgVO;
}
}
第五步:創(chuàng)建一個(gè)測(cè)試服務(wù)端接口的API
import的類(lèi)和注入的RestTemplate:
package com.oysept.controller;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import com.oysept.vo.MsgVO;
/**
* 客戶(hù)端, 調(diào)用服務(wù)端提供的接口
* @author ouyangjun
*/
@RestController
public class ClientController {
// 使用默認(rèn)請(qǐng)求方式
@Autowired
@Qualifier(value = "restTemplate")
private RestTemplate restTemplate;
// 在此處添加客戶(hù)端測(cè)試代碼
}
1、GET請(qǐng)求
// 直接在瀏覽中輸入訪(fǎng)問(wèn)地址: http://localhost:8080/client/get
@RequestMapping(value = "/client/get", method = RequestMethod.GET)
public String get() {
// 無(wú)參GET請(qǐng)求
String get = restTemplate.getForObject("http://localhost:8080/server/get", String.class);
System.out.println("==>/server/get return: " + get);
// 帶參GET請(qǐng)求
String getParam = restTemplate.getForObject("http://localhost:8080/server/get/param?param=111222333444", String.class);
System.out.println("==>/server/get/param return: " + getParam);
// 帶參GET url請(qǐng)求
String getUrlParam = restTemplate.getForObject("http://localhost:8080/server/get/url/{one}/{two}", String.class, "AAAA", "BBBB");
System.out.println("==>/server/get/url/{one}/{two} return: " + getUrlParam);
// 帶參GET url請(qǐng)求
Map<String, String> vars = new HashMap<String, String>();
vars.put("one", "HHHH");
vars.put("two", "EEEE");
String getUrlVars = restTemplate.getForObject("http://localhost:8080/server/get/url/{one}/{two}", String.class, vars);
System.out.println("==>/server/get/url/{one}/{two} return: " + getUrlVars);
// 無(wú)參GET請(qǐng)求, 返回List
@SuppressWarnings("unchecked")
List<String> getList = restTemplate.getForObject("http://localhost:8080/server/get/list", List.class);
System.out.println("==>/server/get/list return: " + getList);
// GET請(qǐng)求, 返回對(duì)象
ResponseEntity<MsgVO> entity = restTemplate.getForEntity("http://localhost:8080/server/get/MsgVO", MsgVO.class);
System.out.println("==>/server/get/list return: " + entity.getBody());
return "GET SUCCESS";
}
2、GET url中傳參請(qǐng)求
// 直接在瀏覽中輸入訪(fǎng)問(wèn)地址: http://localhost:8080/client/get/request
// GET請(qǐng)求, url參數(shù), 在表頭中添加參數(shù)
@RequestMapping(value = "/client/get/request", method = RequestMethod.GET)
public String getRequest() {
// url中參數(shù)
Map<String, String> vars = new HashMap<String, String>();
vars.put("one", "HHHH");
vars.put("two", "EEEE");
// 請(qǐng)求地址
String uriTemplate = "http://localhost:8080/server/get/url/{one}/{two}";
// 給URL地址encode轉(zhuǎn)碼
URI uri = UriComponentsBuilder.fromUriString(uriTemplate).buildAndExpand(vars).toUri();
// GET請(qǐng)求參數(shù)
RequestEntity<Void> requestEntity =
RequestEntity.get(uri)
.header("MyHeader", "aaabbbcccddd")
.build();
// 響應(yīng)
ResponseEntity<String> response = restTemplate.exchange(requestEntity, String.class);
// 結(jié)果
System.out.println("==>/get/request header: " + response.getHeaders().getFirst("MyHeader"));
System.out.println("==>/get/request body: " + response.getBody());
return "POST SUCCESS";
}
3、POST application/x-www-form-urlencoded表單傳參請(qǐng)求
// 直接在瀏覽中輸入訪(fǎng)問(wèn)地址: http://localhost:8080/client/postForm
// POST請(qǐng)求, form表單入?yún)?
@RequestMapping(value = "/client/postForm", method = RequestMethod.GET)
public String postForm() {
// uri
String uriTemplate = "http://localhost:8080/server/post/form";
// 設(shè)置請(qǐng)求頭為form形式: application/x-www-form-urlencoded
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// 設(shè)置參數(shù), 和MsgVO中變量名對(duì)應(yīng)
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("msgKey", "1234");
map.add("msgValue", "TestTest");
// 封裝請(qǐng)求參數(shù)
HttpEntity<MultiValueMap<String, String>> requestb = new HttpEntity<MultiValueMap<String, String>>(map,
headers);
ResponseEntity<String> response = restTemplate.postForEntity(uriTemplate, requestb, String.class);
System.out.println("==>/server/post/form return: " + response.getBody());
return "POST SUCCESS";
}
4、POST application/json JSON傳參請(qǐng)求
// 直接在瀏覽中輸入訪(fǎng)問(wèn)地址: http://localhost:8080/client/postJson
// POST請(qǐng)求, JSON入?yún)?
@RequestMapping(value = "/client/postJson", method = RequestMethod.GET)
public String postJson() {
// json入?yún)?
MsgVO vo = new MsgVO();
vo.setMsgKey("TTT");
vo.setMsgValue("KKK");
String uriTemplate = "http://localhost:8080/server/post/json";
URI uri = UriComponentsBuilder.fromUriString(uriTemplate).buildAndExpand().toUri();
RequestEntity<MsgVO> requestEntity =
RequestEntity.post(uri)
.header("Content-Type", "application/json; charset=UTF-8")
.body(vo);
ResponseEntity<MsgVO> response = restTemplate.exchange(requestEntity, MsgVO.class);
System.out.println("==>/server/post/json return: " + response.getBody());
return "POST SUCCESS";
}
項(xiàng)目結(jié)構(gòu)圖:

以上這篇SpringBoot RestTemplate GET POST請(qǐng)求的實(shí)例講解就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
java面試try-with-resources問(wèn)題解答
這篇文章主要介紹了java面試try-with-resources問(wèn)題解答,?這個(gè)語(yǔ)句的作用是,確保該語(yǔ)句執(zhí)行之后,關(guān)閉每一個(gè)資源,也就是說(shuō)它確保了每個(gè)資源都在生命周期結(jié)束之后被關(guān)閉2022-07-07
SpringSecurity實(shí)現(xiàn)動(dòng)態(tài)權(quán)限校驗(yàn)的過(guò)程
Spring Security過(guò)濾器鏈中,AuthorizationFilter的authorizationManager是我們要找的組件,該組件的check方法已被棄用,推薦使用authorize方法,最終通過(guò)接口路徑和權(quán)限進(jìn)行校驗(yàn),本文給大家介紹SpringSecurity實(shí)現(xiàn)動(dòng)態(tài)權(quán)限校驗(yàn)的相關(guān)知識(shí),感興趣的朋友一起看看吧2025-02-02
SpringBoot中使用SpringSecurity進(jìn)行權(quán)限控制的示例代碼
本文將詳細(xì)介紹如何在Spring Boot應(yīng)用程序中使用Spring Security進(jìn)行權(quán)限控制,我們將探討Spring Security的基本概念,以及如何使用Spring Security實(shí)現(xiàn)認(rèn)證和授權(quán),需要的朋友可以參考下2024-02-02
Springboot實(shí)現(xiàn)密碼的加密解密
這篇文章主要為大家詳細(xì)介紹了Springboot實(shí)現(xiàn)密碼的加密解密,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-11-11
Java及數(shù)據(jù)庫(kù)對(duì)日期進(jìn)行格式化方式
這篇文章主要介紹了Java及數(shù)據(jù)庫(kù)對(duì)日期進(jìn)行格式化方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
Java8深入學(xué)習(xí)系列(三)你可能忽略了的新特性
一提到Java 8就只能聽(tīng)到lambda,但這不過(guò)是其中的一個(gè)而已,Java 8還有許多新的特性,有一些功能強(qiáng)大的新類(lèi)或者新的用法,還有一些功能則是早就應(yīng)該加到Java里了,所以下面這篇文章主要給大家介紹了關(guān)于Java8中大家可能忽略了的一些新特性,需要的朋友可以參考下。2017-08-08
Java使用線(xiàn)程同步解決線(xiàn)程安全問(wèn)題詳解
線(xiàn)程安全是多線(xiàn)程編程時(shí)的計(jì)算機(jī)程序代碼中的一個(gè)概念。在擁有共享數(shù)據(jù)的多條線(xiàn)程并行執(zhí)行的程序中,線(xiàn)程安全的代碼會(huì)通過(guò)同步機(jī)制保證各個(gè)線(xiàn)程都可以正常且正確的執(zhí)行,不會(huì)出現(xiàn)數(shù)據(jù)污染等意外情況2022-05-05
Java中的Web MVC簡(jiǎn)介_(kāi)動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
MVC模型是一種架構(gòu)型的模式,本身不引入新功能,只是幫助我們將開(kāi)發(fā)的結(jié)構(gòu)組織的更加合理,使展示與模型分離、流程控制邏輯、業(yè)務(wù)邏輯調(diào)用與展示邏輯分離2017-09-09

