简体   繁体   中英

HTTP Delete with Request Body issues

Can anyone explain the following:

package com.foo.bar;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import org.springframework.util.FileCopyUtils;

public class ATest {

    public static void main(String[] args) throws Exception {
       try {
           final String payload = "{\"parentExecutor\":\"foo1233\"}";
           URL url = new URL("http://localhost/notes");
           final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
           connection.setRequestMethod("DELETE");
           connection.setRequestProperty("Accept", "application/json");
           connection.setRequestProperty("Content-Type", "application/json");
           FileCopyUtils.copy(payload.getBytes(), connection.getOutputStream());
           connection.connect();
           final InputStream is = connection.getInputStream();
           int b = is.read();
           String result = "";
           while (b != -1) {
               result += (char) b;
               b = is.read();
           }
           System.out.println(connection.getResponseCode());
           System.out.println(result);
           is.close();
       }
       catch (final ProtocolException e) {
          e.printStackTrace();
       }
   }
}

The example above throws the following exception:

java.net.ProtocolException: cannot write to a URLConnection if doOutput=false - call setDoOutput(true)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:995)
    at com.foo.bar.ATest.main(ATest.java:24)

However if I add a call to setDoOutput(true) , the following exception is thrown:

java.net.ProtocolException: HTTP method DELETE doesn't support output
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1004)
    at com.foo.bar.ATest.main(ATest.java:25)

Then, if I change the protocol from http to https no exception is thrown and I get back the expected response code and content from the server. I looked at the source code and can follow the calls and trace where the exceptions are happening, but why would it be OK to make such a request via HTTPS but not HTTP?

This is a limitation (I'd consider it to be a bug or at least a stupid feature) of HttpURLConnection . You're at least not the only one who encounters this when dealing with REST webservices using URLConnection .

Consider using Apache HttpComponents Client instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM