从HttpURLConnection Invalid HTTP method: PATCH
尝试其他解决方案后我在这里写我的问题。 我得到无效的HTTP方法:使用JAVA 7的PATCH异常。 更新JAVA不是选项,所以我必须坚持使用变通办法。
我正在使用Invocation来调用这样的请求
Invocation invoke = reqBuilder.build(getHTTPVerb(), Entity.entity(requestJSON, MediaType.APPLICATION_JSON));
getWebTarget().request(MediaType.APPLICATION_JSON).header("Authorization", getAuthorization()).accept(MediaType.APPLICATION_JSON);
getHTTPVerb()返回String" POST"或PATCH。
使用补丁请求我遇到了问题。
在上述问题中,我没有尝试过一个解决方案:
conn.setRequestProperty("X-HTTP-Method-Override", "PATCH");
conn.setRequestMethod("POST");
conn是HttpURLConnection实例
但我不知道如何从Invocation类或任何属性中获取HttpURLConnection。
任何指针或帮助都将受到高度赞赏。
由于
答案 0 :(得分:0)
带有Apache http客户端的PATCH方法示例:
try {
//This is just to avoid ssl hostname verification and to trust all, you can use simple Http client also
CloseableHttpClient httpClient = HttpClientBuilder.create().setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, TrustAllStrategy.INSTANCE).build())
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
HttpPatch request = new HttpPatch(REST_SERVICE_URL);
StringEntity params = new StringEntity(JSON.toJSONString(payload), ContentType.APPLICATION_JSON);
request.setEntity(params);
request.addHeader(org.apache.http.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
request.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
request.addHeader(HttpHeaders.AUTHORIZATION, OAuth2AccessToken.BEARER_TYPE + " " + accessToken);
HttpResponse response = httpClient.execute(request);
String statusCode = response.getStatusLine().getStatusCode();
} catch (Exception ex) {
// handle exception here
}
RestTemplate的等效示例:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", OAuth2AccessToken.BEARER_TYPE + " " + accessToken);
final HttpEntity<String> entity = new HttpEntity<String>(JSON.toJSONString(payload), headers);
RestTemplate restTemplate = new RestTemplate();
try {
ResponseEntity<String> response = restTemplate.exchange(REST_SERVICE_URL, HttpMethod.PATCH, entity, String.class);
String statusCode = response.getStatusCode();
} catch (HttpClientErrorException e) {
// handle exception here
}