任何人都可以解释以下内容:
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();
}
}
}
上面的示例抛出以下异常:
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)
但是,如果我添加对 setDoOutput(true)的调用,则会抛出以下异常:
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)
然后,如果我将协议从 http 更改为 https ,则不会抛出任何异常,我会从服务器返回预期的响应代码和内容。我查看了源代码,可以跟踪调用并跟踪异常发生的位置,但为什么通过HTTPS而不是HTTP发出这样的请求呢?
答案 0 :(得分:6)
这是HttpURLConnection
的限制(我认为它是一个错误或至少是一个愚蠢的功能)。在使用URLConnection
处理REST网络服务时,您至少遇到not the only one。