在以HTTP发送请求的时候,需要为请求设置请求的方式,常见的请求方式有PUT,POST,GET,DELETE方式等。在使用JAVA语言发送DELETE请求的时候,JAVA的JDK自身提供的HttpUrlConnection对象会默认认为DELETE方式的请求是不需要带请求体的,所以当使用如下代码进行DELETE方式的HTTP请求时,
private String f(List<String> list) throws IOException {
URL url = new URL("www.163.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("DELETE");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("name", "robben");
connection.setRequestProperty("content-type", "text/html");
OutputStreamWriter out = new OutputStreamWriter(
connection.getOutputStream(), "8859_1");
// 将要传递的集合转换成JSON格式
JSONArray jsonArray = JSONArray.fromObject(list);
// 组织要传递的参数
out.write("" + jsonArray);
out.flush();
out.close();
// 获取返回的数据
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line = null;
StringBuffer content = new StringBuffer();
while ((line = in.readLine()) != null) {
// line 为返回值,这就可以判断是否成功
content.append(line);
}
in.close();
return content.toString();
}
JVM就会抛出java.net.ProtocolException: HTTP method DELETE doesn't support output
的异常,来提示我们不能向一个DELETE方式的HTTP请求中写入请求体。
但是如果一定要向DELETE方式的HTTP请求呢?其实也有办法,这里可以使用apache的HttpClient。