How to set HTTP request MOVE using HttpURLConnecti

2019-08-14 16:57发布

问题:

How to set HTTP request method MOVE using HttpURLConnection ?

Using HttpURLConnection or libraries that rely on that class, the code is throwing an exception Caused by: java.net.ProtocolException: Invalid HTTP method: MOVE. So I guess the MOVE method is not supported by the Java platform.

Is there a patch or workaround for this issue / limitation? The workaround could be another java library for creating HTTP requests.

EDIT: Note that the MOVE verb is supported WebDav HTTP extension. There is also PATCH extension that was later added to the protocol.

For reference here is SkyDrive API with the move feature we are trying to implement.

Note that the Ruby platform supports the MOVE method. I wonder why java does not supports or even allow those extensions.

回答1:

It's a bug in HttpURLConnection. If you don't want to switch to a different library, you can try to overwrite the method using introspection (yes, that's what Jersey does, see http://java.net/jira/browse/JERSEY-639)



回答2:

If the server supports it, you can try making a POST request with an X-HTTP-Method-Override: MOVE header.



回答3:

I prefer using Apache Http-Components Client. It has a custom networking implementation, thus using non-standard HTTP methods like MOVE or PATCH are possible:

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpUriRequest moveRequest = RequestBuilder
            .create("MOVE")
            .setUri("http://example.com")
            .build();        
CloseableHttpResponse response = httpclient.execute(moveRequest);

Maven Coordinates:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.2+</version>
</dependency>