spring boot 使用 RestTemplate 进行web请求
默认的 new RestTemplate() 不支持 PATCH
RestTemplate client = new RestTemplate();
执行会报错如下
报错 java.net.ProtocolException: Invalid HTTP method: PATCH
可通过 使用指定 请求工厂 HttpComponentsClientHttpRequestFactory的方式来处理,代码如下
RestTemplate client = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
完整代码如下
public static String doPatchRequest(String url, HttpHeaders headers, String json) {
try {
// 需要指定工厂 HttpComponentsClientHttpRequestFactory
RestTemplate client = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
HttpMethod method = HttpMethod.PATCH;
headers.add("Accept", "application/json");
headers.add("Content-Type", "application/json");
HttpEntity<String> requestEntity = new HttpEntity<>(json, headers);
// 执行HTTP请求,将返回的结构使用String类格式化
ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);
if (response.getStatusCodeValue() == 200) {
return response.getBody();
} else {
log.info("PATCH请求:{}返回失败,返回码:{}", url, response.getStatusCodeValue());
return DataConstants.RESULT_FAILED;
}
} catch (Exception ex) {
log.error("PATCH请求异常:" + url, ex);
return DataConstants.RESULT_FAILED;
}
}
调用
public String updateProject(String authToken, String projectId, String jsonProject) {
String url = this.host + URI_PROJECT + "/" + projectId;
HttpHeaders headers = new HttpHeaders();
headers.set(AUTH_KEY, TOKEN + authToken);
return RestUtil.doPatchRequest(url, headers, jsonProject);
}