之前的开发过程中遇到过各种各样的接口对接,有WebService也有Restful的接口,通讯方式也是多种多样。对于模拟HTTP请求,一直是使用HttpClient的。这里顺便普及一下Http请求的几个方法:
(1)GET:通过请求URI得到资源
(2)POST:用于添加新的内容
(3)PUT:用于修改某个内容,若不存在则添加
(4)DELETE:删除某个内容
(5)OPTIONS :询问可以执行哪些方法
(6)HEAD :类似于GET, 但是不返回body信息,用于检查对象是否存在,以及得到对象的元数据
(7)CONNECT :用于代理进行传输,如使用SSL
(8)TRACE:用于远程诊断服务器
最近的几个项目都开始使用SpringBoot了,突然想到Spring全家桶里面会不会有一种代码习惯更贴近Spring体系的接口交互的方式?简单的使用搜索引擎查找一下,就找到了RestTemplate。
RestTemplate:Spring基于HttpClient封装开发的一个客户端编程工具包,遵循命名约定习惯,方法名由 Http方法 + 返回对象类型 组成。
HTTP各种方法对应 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方法请求一个对象,三个参数分别是“接口地址”、“参数”、“实体类”。
JSONObject params = new JSONObject();
params.put("cameras", cameras);
ResponseEntity responseEntity =restTemplate.postForObject("http://localhost/getUser", params, User.class);
在实际开发过程中,在利用到PATCH方法时会抛出错误:
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
查阅一翻资料之后发现,RestTemplate工厂类的默认实现中,不支持使用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自己的实现,下面是依赖了httpclient包后的实现
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