1.patch请求异常
// 本来我是使用post请求的,结果写代码的时候误写了patch请求,结果出现了异常
RestTemplate restTemplate = new RestTemplate();
restTemplate.postForObject(...); // post是没问题的
//
RestTemplate restTemplate = new RestTemplate();
restTemplate.patchForObject(...); // patch请求出现了问题
2.解决办法
// 使用了HttpComponentsClientHttpRequestFactory
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
RestTemplate restTemplate = new RestTemplate(requestFactory);
3. 原因
1.查看源码我发现,RestTemplate的请求默认是由ClientHttpRequestFactory 进行创建的
private ClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
2.然后进入ClientHttpRequestFactory类,去查看是怎么创建的,这里可以看到创建请求的方法中调用了HttpURLConnection类进行连接。
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
HttpURLConnection connection = this.openConnection(uri.toURL(), this.proxy);
this.prepareConnection(connection, httpMethod.name());
return (ClientHttpRequest)(this.bufferRequestBody ? new SimpleBufferingClientHttpRequest(connection, this.outputStreaming) : new SimpleStreamingClientHttpRequest(connection, this.chunkSize, this.outputStreaming));
}
3.因此我又进入了HttpURLConnection类,发现这个连接不支持patch请求
// 在package java.net;包下面
/* valid HTTP methods */
private static final String[] methods = {
"GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE"
};
4.查看HttpComponentsClientHttpRequestFactory类源码我们可以发现它是支持patch请求的
// 在org.springframework.http.client;包下
protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
switch(httpMethod) {
case GET:
return new HttpGet(uri);
case HEAD:
return new HttpHead(uri);
case POST:
return new HttpPost(uri);
case PUT:
return new HttpPut(uri);
case PATCH:
return new HttpPatch(uri);
case DELETE:
return new HttpComponentsClientHttpRequestFactory.HttpDelete(uri);
case OPTIONS:
return new HttpOptions(uri);
case TRACE:
return new HttpTrace(uri);
default:
throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod);
}
}