HTTP删除请求正文问题 [英] 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)
但是,如果我添加对 setDoOutput(true)的调用,则会抛出以下异常:
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)
然后,如果我将协议从 http 更改为 https ,则不会抛出任何异常,我会从中获取预期的响应代码和内容服务器。我查看了源代码,可以跟踪调用并跟踪异常发生的位置,但为什么通过HTTPS而不是HTTP发出这样的请求呢?
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?
推荐答案
这是 HttpURLConnection
的限制(我认为它是一个错误或至少是一个愚蠢的功能)。您至少并不是唯一一个在使用 URLConnection
处理REST Web服务时遇到此问题的人。
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
.
考虑使用<改为使用href =http://hc.apache.org/httpcomponents-client-ga/> Apache HttpComponents客户端。
这篇关于HTTP删除请求正文问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!