之前的开发过程中遇到过各种各样的接口对接,有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方法 + 返回对象类型 组成。



public JSONObjectgetAccountByPhone(String phone) {
long timestamp = System.currentTimeMillis() /1000;
String sign = getSign(timestamp);
ResponseEntity responseEntity =restTemplate.getForEntity(colour.getHost() + ColourUrl.USER_QUERY +"?ts=" + timestamp +"&sign=" + sign +"&appID=" +colour.getAppId() +"&access_token=" + getAccessToken(timestamp, sign) +"&mobile=" + phone, JSONObject.class);
return responseEntity.getBody().getJSONObject("content");
}


在实际开发过程中,在利用到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>


测试已经搞定!


作者:森林木马

java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names mus...

java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffe...

java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must b

一、错误描述java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens二、错误原因由于在是本地电脑测试请求数据列表的,然后在代码里写的请求是https的,三、解决方案将https改为http即可解决。完结!..