问题
After trying other solutions from HttpURLConnection Invalid HTTP method: PATCH
I am writing my problem here. I am getting Invalid HTTP Method :PATCH Exception with JAVA 7. Updating JAVA is not in option so i have to stick to the Workarounds.
I am using Invocation to invoke the request like this
Invocation invoke = reqBuilder.build(getHTTPVerb(), Entity.entity(requestJSON, MediaType.APPLICATION_JSON));
getWebTarget().request(MediaType.APPLICATION_JSON).header("Authorization", getAuthorization()).accept(MediaType.APPLICATION_JSON);
getHTTPVerb() returns String "POST" or PATCH.
With Patch Request i am having problem.
In the mentioned Question, i have not tried one solution with:
conn.setRequestProperty("X-HTTP-Method-Override", "PATCH");
conn.setRequestMethod("POST");
conn is HttpURLConnection instance
But i am not sure how can i get HttpURLConnection from Invocation class or any property.
Any Pointers or help would be highly appreciated.
Thanks
回答1:
An example of PATCH method with apache http client:
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
}
Equivalent example with 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
}
来源:https://stackoverflow.com/questions/42026770/invalid-http-method-patch