最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring RestTemplate使用方法示例總結(jié)

 更新時(shí)間:2025年04月12日 09:24:39   作者:申城異鄉(xiāng)人  
這篇文章主要介紹了Spring RestTemplate使用方法示例總結(jié),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧

1. 引入依賴

首先,需要確認(rèn)項(xiàng)目中是否直接或者間接引入過spring-web依賴,如果沒有引入過,需要在pom.xml中添加以下代碼引入依賴:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.3.24.RELEASE</version>
</dependency>

2. 發(fā)送GET請求

使用RestTemplate發(fā)送GET請求主要有getForObject()getForEntity()2個(gè)方法,每個(gè)方法分別提供了3種不同的重載。

2.1 使用getForObject發(fā)送GET請求(無參數(shù))

使用getForObject()實(shí)現(xiàn):

RestTemplate restTemplate = new RestTemplate();
String url = "https://www.example.com/getCurrentEnv";
String response = restTemplate.getForObject(url, String.class);
System.out.println(response);

假設(shè)以上接口返回的報(bào)文為:

{
    "serverAddress": "www.example.dev.com",
    "env": "dev"
}

也可以直接解析為自定義的類型:

import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class EnvInfo {
    private String serverAddress;
    private String env;
}
RestTemplate restTemplate = new RestTemplate();
String url = "https://www.example.com/getCurrentEnv";
EnvInfo response = restTemplate.getForObject(url, EnvInfo.class);
System.out.println(JSON.toJSONString(response));

2.2 使用getForEntity發(fā)送GET請求(無參數(shù))

也可以使用getForEntity()實(shí)現(xiàn)和2.1同樣的功能,代碼如下所示:

RestTemplate restTemplate = new RestTemplate();
String url = "https://www.example.com/getCurrentEnv";
ResponseEntity<EnvInfo> responseEntity = restTemplate.getForEntity(url, EnvInfo.class);
if (responseEntity.getStatusCode() == HttpStatus.OK) {
    EnvInfo response = responseEntity.getBody();
    System.out.println(JSON.toJSONString(response));
}

2.3 使用getForObject發(fā)送GET請求(帶參數(shù))

第一種方法是直接在url上拼接上參數(shù),如下所示:

RestTemplate restTemplate = new RestTemplate();
String url = "https://www.example.com/getDataList?pageIndex=1&pageSize=20";
EnvInfo response = restTemplate.getForObject(url, EnvInfo.class);
System.out.println(JSON.toJSONString(response));

第二種方法是使用占位符添加參數(shù),如下所示:

RestTemplate restTemplate = new RestTemplate();
String url = "https://www.example.com/getDataList?pageIndex={1}&pageSize={2}";
EnvInfo response = restTemplate.getForObject(url, EnvInfo.class, 1, 20);
System.out.println(JSON.toJSONString(response));

以上代碼也可以替換為:

RestTemplate restTemplate = new RestTemplate();
String url = "https://www.example.com/getDataList?pageIndex={pageIndex}&pageSize={pageSize}";
Map<String, String> uriVariables = new HashMap<>();
uriVariables.put("pageIndex", "1");
uriVariables.put("pageSize", "20");
EnvInfo response = restTemplate.getForObject(url, EnvInfo.class, uriVariables);
System.out.println(JSON.toJSONString(response));

注意事項(xiàng):

uriVariables中的key必須和url中的占位符名稱一致,否則會拋出異常:

java.lang.IllegalArgumentException: Map has no value for 'pageIndex'

第三種方法是使用UriComponentsBuilder添加參數(shù),該種方法相比于前兩種方法更加靈活,可以實(shí)現(xiàn)動態(tài)添加參數(shù),代碼如下所示:

RestTemplate restTemplate = new RestTemplate();
String httpUrl = "https://www.example.com/getDataList";
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromHttpUrl(httpUrl);
uriComponentsBuilder.queryParam("pageIndex", 1);
uriComponentsBuilder.queryParam("pageSize", 20);
String url = uriComponentsBuilder.toUriString();
EnvInfo response = restTemplate.getForObject(url, EnvInfo.class);
System.out.println(JSON.toJSONString(response));

2.4 使用getForEntity發(fā)送GET請求(帶參數(shù))

也可以使用getForEntity()實(shí)現(xiàn)和2.3同樣的功能,代碼如下所示:

RestTemplate restTemplate = new RestTemplate();

String httpUrl = "https://www.example.com/getDataList";
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromHttpUrl(httpUrl);
uriComponentsBuilder.queryParam("pageIndex", 1);
uriComponentsBuilder.queryParam("pageSize", 20);

String url = uriComponentsBuilder.toUriString();
ResponseEntity<EnvInfo> responseEntity = restTemplate.getForEntity(url, EnvInfo.class);
if (responseEntity.getStatusCode() == HttpStatus.OK) {
    EnvInfo response = responseEntity.getBody();
    System.out.println(JSON.toJSONString(response));
}

2.5 getForObject與getForEntity的區(qū)別

getForEntity()getForObject()相比,返回值用了ResponseEntity進(jìn)行封裝,可以多獲取到以下2種信息:

  • HTTP狀態(tài)碼
  • Response Headers

代碼示例:

RestTemplate restTemplate = new RestTemplate();
String httpUrl = "https://www.example.com/getDataList";
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromHttpUrl(httpUrl);
uriComponentsBuilder.queryParam("pageIndex", 1);
uriComponentsBuilder.queryParam("pageSize", 20);
String url = uriComponentsBuilder.toUriString();
ResponseEntity<EnvInfo> responseEntity = restTemplate.getForEntity(url, EnvInfo.class);
System.out.println("statusCode: " + responseEntity.getStatusCode().toString());
System.out.println("statusCodeValue: " + responseEntity.getStatusCodeValue());
responseEntity.getHeaders().forEach((key, values) -> {
    System.out.println(key + ": " + values);
});

輸出結(jié)果:

statusCode: 200
statusCodeValue: 200
Server: [openresty]
Date: [Thu, 10 Apr 2025 05:39:02 GMT]
Content-Type: [application/json]
Transfer-Encoding: [chunked]
Connection: [keep-alive]

其中Response Headers輸出部分和Chrome瀏覽器Network中的Response Headers是一致的:

2.6 發(fā)送GET請求(帶參數(shù)及請求頭)

一般情況下,請求第三方接口都需要簽名、時(shí)間戳等請求頭,但getForObject()getForEntity()都不支持,

此時(shí)需要使用exchange()方法,代碼如下所示:

RestTemplate restTemplate = new RestTemplate();
String httpUrl = "https://www.example.com/getDataList";
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromHttpUrl(httpUrl);
uriComponentsBuilder.queryParam("pageIndex", 1);
uriComponentsBuilder.queryParam("pageSize", 20);
HttpHeaders headers = new HttpHeaders();
headers.set("signature", "3045022100875efcef9eb54626bb0168a6baa7c61265d0001d49243f");
headers.set("timestamp", String.valueOf(System.currentTimeMillis()));
String url = uriComponentsBuilder.toUriString();
ResponseEntity<EnvInfo> responseEntity = restTemplate.exchange(url,
        HttpMethod.GET,
        new HttpEntity<>(headers),
        EnvInfo.class);
if (responseEntity.getStatusCode() == HttpStatus.OK) {
    EnvInfo response = responseEntity.getBody();
    System.out.println(JSON.toJSONString(response));
}

3. 發(fā)送POST請求

使用RestTemplate發(fā)送POST請求主要有postForObject()postForEntity()2個(gè)方法,每個(gè)方法分別提供了3種不同的重載。

3.1 發(fā)送POST請求(帶參數(shù)、json方式)

使用postForObject()實(shí)現(xiàn):

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
LoginParams loginParams = new LoginParams();
loginParams.setUsername("zhangsan");
loginParams.setPassword("123456");
HttpEntity<LoginParams> request = new HttpEntity<>(loginParams, headers);
String url = "https://www.example.com/login";
String response = restTemplate.postForObject(url, request, String.class);
System.out.println(response);

LoginParams的定義如下所示:

import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class LoginParams {
    private String username;
    private String password;
}

假設(shè)以上接口返回的報(bào)文為:

{
    "code": 200,
    "expire": "2025-04-11 14:42:22",
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NDQzNTM3NDIsImlkZW50aXR5"
}

也可以直接解析為自定義的類型:

import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class LoginResponse {
    private Integer code;
    private String expire;
    private String token;
}
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
LoginParams loginParams = new LoginParams();
loginParams.setUsername("zhangsan");
loginParams.setPassword("123456");
HttpEntity<LoginParams> request = new HttpEntity<>(loginParams, headers);
String url = "https://www.example.com/login";
LoginResponse response = restTemplate.postForObject(url, request, LoginResponse.class);
System.out.println(JSON.toJSONString(response));

也可以使用postForEntity()實(shí)現(xiàn)同樣的功能,代碼如下所示:

ResponseEntity<LoginResponse> responseEntity = restTemplate.postForEntity(url, request, LoginResponse.class);
if (responseEntity.getStatusCode() == HttpStatus.OK) {
    LoginResponse response = responseEntity.getBody();
    System.out.println(JSON.toJSONString(response));
}

3.2 發(fā)送POST請求(帶參數(shù)、form表單方式)

使用postForObject()實(shí)現(xiàn):

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("username", "zhangsan");
map.add("password", "123456");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
String url = "https://www.example.com/login";
LoginResponse response = restTemplate.postForObject(url, request, LoginResponse.class);
System.out.println(JSON.toJSONString(response));

也可以使用postForEntity()實(shí)現(xiàn)同樣的功能,代碼如下所示:

ResponseEntity<LoginResponse> responseEntity = restTemplate.postForEntity(url, request, LoginResponse.class);
if (responseEntity.getStatusCode() == HttpStatus.OK) {
    LoginResponse response = responseEntity.getBody();
    System.out.println(JSON.toJSONString(response));
}

3.3 postForObject與postForEntity的區(qū)別

postForObject()postForEntity()的區(qū)別,與getForEntity()getForObject()的區(qū)別一樣,

返回值用了ResponseEntity進(jìn)行封裝。

4. 超時(shí)時(shí)間設(shè)置

如果需要自定義HTTP請求的連接超時(shí)時(shí)間和數(shù)據(jù)傳輸超時(shí)時(shí)間,代碼如下所示:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
    @Value("${restTemplate.connectTimeout:5000}")
    private int connectTimeout;
    @Value("${restTemplate.readTimeout:10000}")
    private int readTimeout;
    @Bean
    public RestTemplate restTemplate() {
        SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        simpleClientHttpRequestFactory.setConnectTimeout(connectTimeout);
        simpleClientHttpRequestFactory.setReadTimeout(readTimeout);
        return new RestTemplate(simpleClientHttpRequestFactory);
    }
}

到此這篇關(guān)于Spring RestTemplate使用方法總結(jié)的文章就介紹到這了,更多相關(guān)Spring RestTemplate使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java數(shù)據(jù)結(jié)構(gòu)之對象的比較

    Java數(shù)據(jù)結(jié)構(gòu)之對象的比較

    比較對象是面向?qū)ο缶幊陶Z言的一個(gè)基本特征,下面這篇文章主要給大家介紹了關(guān)于Java數(shù)據(jù)結(jié)構(gòu)之對象的比較,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-02-02
  • 解決java junit單元測試@Test報(bào)錯(cuò)的問題

    解決java junit單元測試@Test報(bào)錯(cuò)的問題

    今天小編就為大家分享一篇解決java junit單元測試@Test報(bào)錯(cuò)的問題,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-11-11
  • Java泛型在集合使用與自定義及繼承上的體現(xiàn)和通配符的使用

    Java泛型在集合使用與自定義及繼承上的體現(xiàn)和通配符的使用

    泛型又稱參數(shù)化類型,是Jdk5.0 出現(xiàn)的新特性,解決數(shù)據(jù)類型的安全性問題,在類聲明或?qū)嵗瘯r(shí)只要指定好需要的具體的類型即可。Java泛型可以保證如果程序在編譯時(shí)沒有發(fā)出警告,運(yùn)行時(shí)就不會產(chǎn)生ClassCastException異常。同時(shí),代碼更加簡潔、健壯
    2021-09-09
  • java從文件中讀取數(shù)據(jù)的六種方法

    java從文件中讀取數(shù)據(jù)的六種方法

    本文主要介紹了java從文件中讀取數(shù)據(jù)的方法,詳細(xì)的介紹了六種方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-11-11
  • java web在高并發(fā)和分布式下實(shí)現(xiàn)訂單號生成唯一的解決方案

    java web在高并發(fā)和分布式下實(shí)現(xiàn)訂單號生成唯一的解決方案

    這篇文章主要介紹了java web在高并發(fā)和分布式下實(shí)現(xiàn)訂單號生成唯一的解決方案,需要的朋友可以參考下
    2017-11-11
  • Mybatis使用命令生成逆向工程的方法

    Mybatis使用命令生成逆向工程的方法

    這篇文章主要介紹了Mybatis使用命令生成逆向工程的方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-01-01
  • Java Swing中JDialog實(shí)現(xiàn)用戶登陸UI示例

    Java Swing中JDialog實(shí)現(xiàn)用戶登陸UI示例

    這篇文章主要介紹了Java Swing中JDialog實(shí)現(xiàn)用戶登陸UI功能,結(jié)合完整實(shí)例形式分析了Swing使用JDialog實(shí)現(xiàn)用戶登陸UI界面窗口功能的步驟與相關(guān)操作技巧,需要的朋友可以參考下
    2017-11-11
  • java實(shí)現(xiàn)猜拳小游戲

    java實(shí)現(xiàn)猜拳小游戲

    這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)猜拳小游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-01-01
  • 淺析SpringBoot中的過濾器和攔截器

    淺析SpringBoot中的過濾器和攔截器

    過濾器和攔截器都是為了在請求到達(dá)目標(biāo)處理器(Servlet或Controller)之前或者之后插入自定義的處理邏輯,下面就跟隨小編來看看它們二者的區(qū)別和具體使用吧
    2024-03-03
  • springboot實(shí)現(xiàn)郵箱發(fā)送(激活碼)功能的示例代碼

    springboot實(shí)現(xiàn)郵箱發(fā)送(激活碼)功能的示例代碼

    這篇文章主要為大家詳細(xì)介紹了如何利用springboot實(shí)現(xiàn)郵箱發(fā)送(激活碼)功能,文中的示例代碼簡潔易懂,有需要的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2023-10-10

最新評論

金阳县| 六枝特区| 陆河县| 永安市| 稷山县| 嘉峪关市| 吉木萨尔县| 凉城县| 岫岩| 社会| 平乡县| 浪卡子县| 永寿县| 长宁县| 扶绥县| 新绛县| 万盛区| 瓦房店市| 湘乡市| 大石桥市| 盐源县| 库尔勒市| 凤凰县| 稻城县| 昭苏县| 樟树市| 农安县| 曲阜市| 天全县| 江川县| 香河县| 成安县| 云林县| 图木舒克市| 诏安县| 资兴市| 凤凰县| 宜章县| 常熟市| 木兰县| 铁岭县|