Jersey http client custom request method

With the following code using jersey :

  <groupId>com.sun.jersey.contribs</groupId> <artifactId>jersey-apache-client4</artifactId> <version>1.13-b01</version> 

I'm having problems using custom query methods like FOOBAR, PATCH, SEARCH, etc. Those that do not exist in httpUrlConnection .

  DefaultClientConfig config = new DefaultClientConfig(); config.getProperties().put(URLConnectionClientHandler.PROPERTY_HTTP_URL_CONNECTION_SET_METHOD_WORKAROUND, true); Client c = Client.create(config); Form f = new Form(); f.add("id", "foobar"); WebResource r = c.resource("http://127.0.0.1/foo"); String methodName = "foobar"; String response = r.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept(MediaType.APPLICATION_JSON_TYPE).header("USER-AGENT", "my-java-sdk /1.1").method(methodName.toUpperCase(), String.class, f); 

The result is the following exception:

  com.sun.jersey.api.client.ClientHandlerException: java.net.ProtocolException: Invalid HTTP method: FOOBAR 

I tried various ways to try to solve this problem without success.

  • http://java.net/jira/browse/JERSEY-639 was implemented above in the config.getProperties() . Still getting the error
  • When I switch to the apache http address, I get 411 errors from the server receiving requests for all requests not related to GET and non-PUT.

In short, I want to implement similar functionality available through Java:

Thanks in advance for your feedback.

+6
source share
2 answers

With Jersey 2.x Client we set property

to true

 Client client = ClientBuilder.newClient(); client.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true); String response = client.target(url).request().method("PATCH", entity, String.class); 
+4
source

This is not a mistake, this is a feature. :)

but seriously. HttpUrlConnection does not allow the use of custom HTTP methods because:

// This restriction will not allow people to use this class for

// experiment with new HTTP methods using java.

So you cannot use other methods except (in java 6): "GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE"

Jersey provides a workaround and uses reflection to omit this check:

 DefaultClientConfig config = new DefaultClientConfig(); config.getProperties().put(URLConnectionClientHandler.PROPERTY_HTTP_URL_CONNECTION _SET_METHOD_WORKAROUND, true); Client c = Client.create(config); WebResource r = c.resource("http://google.com"); String reponse = r.method("FOOBAR", String.class); 
+3
source

Source: https://habr.com/ru/post/916110/


All Articles