之前的開發(fā)過程中遇到過各種各樣的接口對接,有WebService也有Restful的接口,通訊方式也是多種多樣蹦哼。對于模擬HTTP請求,一直是使用HttpClient的要糊。這里順便普及一下Http請求的幾個方法:
(1)GET:通過請求URI得到資源
(2)POST:用于添加新的內(nèi)容
(3)PUT:用于修改某個內(nèi)容纲熏,若不存在則添加
(4)DELETE:刪除某個內(nèi)容
(5)OPTIONS :詢問可以執(zhí)行哪些方法
(6)HEAD :類似于GET, 但是不返回body信息,用于檢查對象是否存在锄俄,以及得到對象的元數(shù)據(jù)
(7)CONNECT :用于代理進(jìn)行傳輸局劲,如使用SSL
(8)TRACE:用于遠(yuǎn)程診斷服務(wù)器
最近的幾個項(xiàng)目都開始使用SpringBoot了,突然想到Spring全家桶里面會不會有一種代碼習(xí)慣更貼近Spring體系的接口交互的方式奶赠?簡單的使用搜索引擎查找一下鱼填,就找到了RestTemplate。
RestTemplate:Spring基于HttpClient封裝開發(fā)的一個客戶端編程工具包毅戈,遵循命名約定習(xí)慣苹丸,方法名由 Http方法 + 返回對象類型 組成。
HTTP各種方法對應(yīng) RestTemplate 中提供的方法
DELETE
delete(String, Object...)
GET
getForObject(String,Class<T>, Object...)
getForEntity(String, Class<T>, Object...)
HEAD
headForHeaders(String, Object...)
OPTIONS
optionsForAllow(String,Object...)
POST
postForLocation(String, Object, Object...)
postForObject(String, Object, Class<T>, Object...)
PUT
put(String, Object, Object...)
所有方法
exchange(String, HttpMethod, org.springframework.http.HttpEntity<?>, java.lang.Class<T>, java.lang.Object...)
execute(String, HttpMethod, RequestCallback, ResponseExtractor<T>, Object...)
使用示例竹祷,簡單粗暴谈跛。postFoObject代表用POST方法請求一個對象,三個參數(shù)分別是“接口地址”塑陵、“參數(shù)”感憾、“實(shí)體類”。
JSONObject params = new JSONObject();
params.put("cameras", cameras);
ResponseEntity responseEntity =restTemplate.postForObject("http://localhost/getUser", params, User.class);
在實(shí)際開發(fā)過程中令花,在利用到PATCH方法時(shí)會拋出錯誤:
org.springframework.web.client.ResourceAccessException: I/O error on PATCH request for "http://localhost:8080/test":Invalid HTTP method: PATCH;
nested exception is java.net.ProtocolException: Invalid HTTP method: PATCH
查閱一翻資料之后發(fā)現(xiàn)阻桅,RestTemplate工廠類的默認(rèn)實(shí)現(xiàn)中,不支持使用PATCH方法兼都,需要將RestTemplate配置類的工廠對象修改為HttpComponentsClientHttpRequestFactory嫂沉,這
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
// SimpleClientHttpRequestFactory factory=new SimpleClientHttpRequestFactory();
// 上一行被注釋掉的是Spring自己的實(shí)現(xiàn),下面是依賴了httpclient包后的實(shí)現(xiàn)
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setConnectTimeout(5000);
factory.setReadTimeout(5000);
return factory;
}
}
另外扮碧,你可能還需要引入httpclient的依賴
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4.1</version>
</dependency>
參考資料:https://stackoverflow.com/questions/29447382/resttemplate-patch-request