Springboot使用RestTemplate进行web请求,默认不支持PATCH的处理方式
Springboot 使用RestTemplate进行web请求,默认不支持PATCH的处理方式
·
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);
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)