之前的开发过程中遇到过各种各样的接口对接,有WebService也有Restful的接口,通讯方式也是多种多样。对于模拟 HTTP请求,一直是使用 HTTPClient的。

先介绍 HTTP请求的几个方法:

  • GET:通过请求URI得到资源
  • POST:用于添加新的内容
  • PUT:用于修改某个内容,若不存在则添加
  • DELETE:删除某个内容
  • OPTIONS :询问可以执行哪些方法
  • HEAD :类似于GET, 但是不返回body信息,用于检查对象是否存在,以及得到对象的元数据
  • CONNECT :用于代理进行传输,如使用SSL
  • TRACE:用于远程诊断服务器

最近的几个项目都开始使用SpringBoot了,突然想到Spring全家桶里面会不会有一种代码习惯更贴近Spring体系的接口交互的方式?简单的使用搜索引擎查找一下,就找到了**RestTemplate**。

RestTemplate:Spring基于 HTTPClient封装开发的一个客户端编程工具包,遵循命名约定习惯,方法名由 HTTP方法 + 返回对象类型 组成。

HTTP各种方法对应 RestTemplate 中提供的方法

返回值方法及描述
voiddelete(String url, Map<String,?> uriVariables)Delete the resources at the specified URI.
voiddelete(String url, Object... uriVariables)Delete the resources at the specified URI.
voiddelete(URI url)Delete the resources at the specified URL.
<T> ResponseEntity<T>exchange(RequestEntity<?> requestEntity, Class<T> responseType)Execute the request specified in the given [RequestEntity]( HTTPs://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/ HTTP/RequestEntity.html) and return the response as [ResponseEntity]( HTTPs://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/ HTTP/ResponseEntity.html).
<T> ResponseEntity<T>exchange(RequestEntity<?> requestEntity, ParameterizedTypeReference<T> responseType)Execute the request specified in the given [RequestEntity]( HTTPs://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/ HTTP/RequestEntity.html) and return the response as [ResponseEntity]( HTTPs://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/ HTTP/ResponseEntity.html).
<T> ResponseEntity<T>exchange(String url, HTTPMethod method, HTTPEntity<?> requestEntity, Class<T> responseType, Map<String,?> uriVariables)Execute the HTTP method to the given URI template, writing the given request entity to the request, and returns the response as [ResponseEntity]( HTTPs://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/ HTTP/ResponseEntity.html).
<T> ResponseEntity<T>exchange(String url, HTTPMethod method, HTTPEntity<?> requestEntity, Class<T> responseType, Object... uriVariables)Execute the HTTP method to the given URI template, writing the given request entity to the request, and returns the response as [ResponseEntity]( HTTPs://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/ HTTP/ResponseEntity.html).
<T> ResponseEntity<T>exchange(String url, HTTPMethod method, HTTPEntity<?> requestEntity, ParameterizedTypeReference<T> responseType, Map<String,?> uriVariables)Execute the HTTP method to the given URI template, writing the given request entity to the request, and returns the response as [ResponseEntity]( HTTPs://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/ HTTP/ResponseEntity.html).
<T> ResponseEntity<T>exchange(String url, HTTPMethod method, HTTPEntity<?> requestEntity, ParameterizedTypeReference<T> responseType, Object... uriVariables)Execute the HTTP method to the given URI template, writing the given request entity to the request, and returns the response as [ResponseEntity]( HTTPs://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/ HTTP/ResponseEntity.html).
<T> ResponseEntity<T>exchange(URI url, HTTPMethod method, HTTPEntity<?> requestEntity, Class<T> responseType)Execute the HTTP method to the given URI template, writing the given request entity to the request, and returns the response as [ResponseEntity]( HTTPs://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/ HTTP/ResponseEntity.html).
<T> ResponseEntity<T>exchange(URI url, HTTPMethod method, HTTPEntity<?> requestEntity, ParameterizedTypeReference<T> responseType)Execute the HTTP method to the given URI template, writing the given request entity to the request, and returns the response as [ResponseEntity]( HTTPs://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/ HTTP/ResponseEntity.html).
<T> Texecute(String url, HTTPMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor, Map<String,?> uriVariables)Execute the HTTP method to the given URI template, preparing the request with the RequestCallback, and reading the response with a ResponseExtractor.
<T> Texecute(String url, HTTPMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor, Object... uriVariables)Execute the HTTP method to the given URI template, preparing the request with the RequestCallback, and reading the response with a ResponseExtractor.
<T> Texecute(URI url, HTTPMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor)Execute the HTTP method to the given URL, preparing the request with the RequestCallback, and reading the response with a ResponseExtractor.
<T> ResponseEntity<T>getForEntity(String url, Class<T> responseType, Map<String,?> uriVariables)Retrieve a representation by doing a GET on the URI template.
<T> ResponseEntity<T>getForEntity(String url, Class<T> responseType, Object... uriVariables)Retrieve an entity by doing a GET on the specified URL.
<T> ResponseEntity<T>getForEntity(URI url, Class<T> responseType)Retrieve a representation by doing a GET on the URL .
<T> TgetForObject(String url, Class<T> responseType, Map<String,?> uriVariables)Retrieve a representation by doing a GET on the URI template.
<T> TgetForObject(String url, Class<T> responseType, Object... uriVariables)Retrieve a representation by doing a GET on the specified URL.
<T> TgetForObject(URI url, Class<T> responseType)Retrieve a representation by doing a GET on the URL .
HTTPHeadersheadForHeaders(String url, Map<String,?> uriVariables)Retrieve all headers of the resource specified by the URI template.
HTTPHeadersheadForHeaders(String url, Object... uriVariables)Retrieve all headers of the resource specified by the URI template.
HTTPHeadersheadForHeaders(URI url)Retrieve all headers of the resource specified by the URL.
Set< HTTPMethod>optionsForAllow(String url, Map<String,?> uriVariables)Return the value of the Allow header for the given URI.
Set< HTTPMethod>optionsForAllow(String url, Object... uriVariables)Return the value of the Allow header for the given URI.
Set< HTTPMethod>optionsForAllow(URI url)Return the value of the Allow header for the given URL.
<T> TpatchForObject(String url, Object request, Class<T> responseType, Map<String,?> uriVariables)Update a resource by PATCHing the given object to the URI template, and return the representation found in the response.
<T> TpatchForObject(String url, Object request, Class<T> responseType, Object... uriVariables)Update a resource by PATCHing the given object to the URI template, and return the representation found in the response.
<T> TpatchForObject(URI url, Object request, Class<T> responseType)Update a resource by PATCHing the given object to the URL, and return the representation found in the response.
<T> ResponseEntity<T>postForEntity(String url, Object request, Class<T> responseType, Map<String,?> uriVariables)Create a new resource by POSTing the given object to the URI template, and returns the response as [HTTPEntity]( HTTPs://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/ HTTP/ HTTPEntity.html).
<T> ResponseEntity<T>postForEntity(String url, Object request, Class<T> responseType, Object... uriVariables)Create a new resource by POSTing the given object to the URI template, and returns the response as [ResponseEntity]( HTTPs://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/ HTTP/ResponseEntity.html).
<T> ResponseEntity<T>postForEntity(URI url, Object request, Class<T> responseType)Create a new resource by POSTing the given object to the URL, and returns the response as [ResponseEntity]( HTTPs://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/ HTTP/ResponseEntity.html).
URIpostForLocation(String url, Object request, Map<String,?> uriVariables)Create a new resource by POSTing the given object to the URI template, and returns the value of the Location header.
URIpostForLocation(String url, Object request, Object... uriVariables)Create a new resource by POSTing the given object to the URI template, and returns the value of the Location header.
URIpostForLocation(URI url, Object request)Create a new resource by POSTing the given object to the URL, and returns the value of the Location header.
<T> TpostForObject(String url, Object request, Class<T> responseType, Map<String,?> uriVariables)Create a new resource by POSTing the given object to the URI template, and returns the representation found in the response.
<T> TpostForObject(String url, Object request, Class<T> responseType, Object... uriVariables)Create a new resource by POSTing the given object to the URI template, and returns the representation found in the response.
<T> TpostForObject(URI url, Object request, Class<T> responseType)Create a new resource by POSTing the given object to the URL, and returns the representation found in the response.
voidput(String url, Object request, Map<String,?> uriVariables)Creates a new resource by PUTting the given object to URI template.
voidput(String url, Object request, Object... uriVariables)Create or update a resource by PUTting the given object to the URI.
voidput(URI url, Object request)Creates a new resource by PUTting the given object to URL.

使用示例,简单粗暴。postForObject代表用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配置类的工厂对象修改为** HTTPComponentsClient HTTPRequestFactory**,这

public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(Client HTTPRequestFactory factory) {
        return new RestTemplate(factory);
    }

    @Bean
    public Client HTTPRequestFactory simpleClient HTTPRequestFactory() {
        // Spring自己的实现
		// SimpleClient HTTPRequestFactory factory = new SimpleClient HTTPRequestFactory();
        
		// 依赖了 HTTPclient包后的实现
         HTTPComponentsClient HTTPRequestFactory factory = new  HTTPComponentsClient HTTPRequestFactory();
        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

文章作者: Administrator
版权声明: 本站所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 if(xyz!=null)
技术分享 java RestTemplate Spring Boot
喜欢就支持一下吧
打赏
微信 微信
支付宝 支付宝