欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring Boot RestTemplate提交表單數(shù)據(jù)的三種方法

 更新時(shí)間:2018年03月08日 15:27:00   作者:蟻方陣  
本篇文章主要介紹了Spring Boot RestTemplate提交表單數(shù)據(jù)的三種方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

在REST接口的設(shè)計(jì)中,利用RestTemplate進(jìn)行接口測試是種常見的方法,但在使用過程中,由于其方法參數(shù)眾多,很多同學(xué)又混淆了表單提交與Payload提交方式的差別,而且接口設(shè)計(jì)與傳統(tǒng)的瀏覽器使用的提交方式又有差異,經(jīng)常出現(xiàn)各種各樣的錯(cuò)誤,如405錯(cuò)誤,或者根本就得不到提交的數(shù)據(jù),錯(cuò)誤樣例如下:

Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 405 Method Not Allowed
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:63)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:531)

1. 用exchange方法提交

exchange既可以執(zhí)行POST方法,還可以執(zhí)行GET,所以應(yīng)用最為廣泛,使用方法如下:

String url = "http://localhost/mirana-ee/app/login";
RestTemplate client = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
// 請勿輕易改變此提交方式,大部分的情況下,提交方式都是表單提交
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// 封裝參數(shù),千萬不要替換為Map與HashMap,否則參數(shù)無法傳遞
MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
// 也支持中文
params.add("username", "用戶名");
params.add("password", "123456");
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
// 執(zhí)行HTTP請求
ResponseEntity<String> response = client.exchange(url, HttpMethod.POST, requestEntity, String.class);
// 輸出結(jié)果
System.out.println(response.getBody());

2. 用postForEntity進(jìn)行提交

postForEntity是對exchange的簡化,僅僅只需要減少HttpMethod.POST參數(shù),如下:

// 上面的代碼完全一樣
// 僅需替換exchange方法
ResponseEntity<String> response = client.postForEntity(url, requestEntity , String.class );

3. 關(guān)于表單提交與Payload提交的差異

在Controller的方法參數(shù)中,如果將“@ModelAttribute”改為“@RequestBody”注解,則此時(shí)的提交方式為Payload方式提交,代碼示例如下:

// 請注意@RequestBody注解
@RequestMapping(value="/login", method=RequestMethod.POST, consumes="application/json")
// 千萬不要畫蛇添足添加@ModelAttribute,否則會(huì)被其覆蓋,如下
// public Account getAccount(@RequestBody@ModelAttribute Account account)
public Account getAccount(@RequestBody Account account) {
  account.setVersion(new Date());
  return account;
}

再次強(qiáng)調(diào)一次,千萬不要畫蛇添足再次添加“@ModelAttribute”,因?yàn)槠鋬?yōu)先級比較高,所以系統(tǒng)會(huì)采用表單方式解析提交內(nèi)容。

對于Payload方式,提交的內(nèi)容一定要是String,且Header要設(shè)置為“application/json”,示例如下:

// 請求地址
String url = "http://localhost/mirana-ee/app/login";
RestTemplate client = new RestTemplate();
// 一定要設(shè)置header
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
// 將提交的數(shù)據(jù)轉(zhuǎn)換為String
// 最好通過bean注入的方式獲取ObjectMapper
ObjectMapper mapper = new ObjectMapper();
Map<String, String> params= Maps.newHashMap();
params.put("username", "國米");
params.put("password", "123456");
String value = mapper.writeValueAsString(params);
HttpEntity<String> requestEntity = new HttpEntity<String>(value, headers);
// 執(zhí)行HTTP請求
ResponseEntity<String> response = client.postForEntity(url, requestEntity , String.class );
System.out.println(response.getBody());

如果內(nèi)容不是以String方式提交,那么一定會(huì)出現(xiàn)以下錯(cuò)誤:

Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 400 Bad Request
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:63)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
    at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:407)

最后需要強(qiáng)調(diào)的是,通過@RequestBody是無法獲取到請求參數(shù),如將上面服務(wù)端的代碼改為如下格式,則肯定得不到數(shù)據(jù),但表單提交則相反。

@RequestMapping(value="/login", consumes="application/json", method=RequestMethod.POST)
public Account getAccount(@RequestBody Account account, HttpServletRequest request) {
  // 肯定得不到參數(shù)值
  System.out.println(request.getParameter("username"));
  account.setVersion(new Date());
  return account;
}

4. HttpEntity的結(jié)構(gòu)

HttpEntity是對HTTP請求的封裝,包含兩部分,header與body,header用于設(shè)置請求頭,而body則用于設(shè)置請求體,所以其的構(gòu)造器如下:

// value為請求體
// header為請求頭
HttpEntity<String> requestEntity = new HttpEntity<String>(value, headers);

5. HttpEntity與uriVariables

在RestTemplate的使用中,HttpEntity用于傳遞具體的參數(shù)值,而uriVariables則用于格式化Http地址,而不是地址參數(shù),正確的用法如下:

// 在地址中加入格式化參數(shù)path
String url = "http://localhost/mirana-ee/app/{path}";
// 準(zhǔn)備格式化參數(shù)
Map<String, String> varParams = Maps.newHashMap();
varParams.put("path", "login");
// 其他代碼略
// 格式化提交地址
ResponseEntity<String> response = client.postForEntity(url, requestEntity , String.class, varParams);

6. 關(guān)于HttpMessageConverter的說明

在網(wǎng)上的很多例子中,我發(fā)現(xiàn)很多人為了處理Payload提交,都添加了自定義的HttpMessageConverter,如下:

// 完全沒有必要
client.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
client.getMessageConverters().add(new StringHttpMessageConverter());

然后,經(jīng)過我查看源碼與調(diào)試發(fā)現(xiàn),RestTemplate內(nèi)置了7種HttpMessageConverter,如下:

1. org.springframework.http.converter.ByteArrayHttpMessageConverter
2. org.springframework.http.converter.StringHttpMessageConverter
3. org.springframework.http.converter.ResourceHttpMessageConverter
4. org.springframework.http.converter.xml.SourceHttpMessageConverter
5. org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter
6. org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter
7. org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
“`

結(jié)論

RestTemplate能大幅簡化了提交表單數(shù)據(jù)的難度,并且附帶了自動(dòng)轉(zhuǎn)換JSON數(shù)據(jù)的功能,但只有理解了HttpEntity的組成結(jié)構(gòu)(header與body),且理解了與uriVariables之間的差異,才能真正掌握其用法。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • SpringBoot 配合 SpringSecurity 實(shí)現(xiàn)自動(dòng)登錄功能的代碼

    SpringBoot 配合 SpringSecurity 實(shí)現(xiàn)自動(dòng)登錄功能的代碼

    這篇文章主要介紹了SpringBoot 配合 SpringSecurity 實(shí)現(xiàn)自動(dòng)登錄功能的代碼,代碼簡單易懂,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-09-09
  • 一篇文章帶你入門java變量與類型

    一篇文章帶你入門java變量與類型

    這篇文章主要給大家介紹了關(guān)于Java基本知識點(diǎn)之變量和數(shù)據(jù)類型的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-08-08
  • springboot微服務(wù)項(xiàng)目集成html頁面的實(shí)現(xiàn)

    springboot微服務(wù)項(xiàng)目集成html頁面的實(shí)現(xiàn)

    本文主要介紹了springboot微服務(wù)項(xiàng)目集成html頁面的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-04-04
  • Spring使用注解存儲Bean對象的方法詳解

    Spring使用注解存儲Bean對象的方法詳解

    在使用學(xué)習(xí)使用 Spring過程中,當(dāng)我們要實(shí)現(xiàn)一個(gè)功能的時(shí)候,先應(yīng)該考慮的是有沒有相應(yīng)的注解是實(shí)現(xiàn)對應(yīng)功能的,Spring 中很多功能的配置都是可以依靠注解實(shí)現(xiàn)的,而本篇中介紹的是使用注解來存儲 Bean 對象
    2023-07-07
  • 如何使用Guava Cache做緩存

    如何使用Guava Cache做緩存

    Cache在ConcurrentHashMap的基礎(chǔ)上提供了自動(dòng)加載數(shù)據(jù)、清除數(shù)據(jù)、get-if-absend-compute的功能,本文給大家介紹如何使用Guava Cache做緩存,感興趣的朋友一起看看吧
    2023-11-11
  • servlet實(shí)現(xiàn)文件上傳與下載功能

    servlet實(shí)現(xiàn)文件上傳與下載功能

    這篇文章主要為大家詳細(xì)介紹了servlet實(shí)現(xiàn)文件上傳與下載功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-03-03
  • Springboot中的@Conditional注解詳解

    Springboot中的@Conditional注解詳解

    這篇文章主要介紹了Springboot中的@Conditional注解詳解,@Conditional來源于spring-context包下的一個(gè)注解,Conditional中文是條件的意思,@Conditional注解它的作用是按照一定的條件進(jìn)行判斷,滿足條件給容器注冊bean,需要的朋友可以參考下
    2023-09-09
  • Java實(shí)現(xiàn)導(dǎo)出Excel功能

    Java實(shí)現(xiàn)導(dǎo)出Excel功能

    通過java中Controller層,來接受請求,數(shù)據(jù)庫查詢到的數(shù)據(jù)進(jìn)行封裝,然后使用ExcelUtils進(jìn)行輸出,接下來通過本文給大家分享Java實(shí)現(xiàn)導(dǎo)出Excel功能的實(shí)例代碼,感興趣的朋友跟隨小編一起看看吧
    2021-11-11
  • springmvc 防止表單重復(fù)提交的兩種方法

    springmvc 防止表單重復(fù)提交的兩種方法

    最近在本地開發(fā)測試的時(shí)候,遇到一個(gè)表單重復(fù)提交的現(xiàn)象。本文主要介紹了springmvc 防止表單重復(fù)提交的兩種方法,感興趣的可以了解一下
    2021-08-08
  • Java中shiro框架和security框架的區(qū)別

    Java中shiro框架和security框架的區(qū)別

    這篇文章主要介紹了Java中shiro框架和security框架的區(qū)別,shiro和security作為兩款流行的功能強(qiáng)大的且易于使用的java安全認(rèn)證框架,在近些年中的項(xiàng)目開發(fā)過程中使用廣泛,今天我們就來一起了解一下兩者的區(qū)別
    2023-08-08

最新評論