最近在测试通过http delete method传参数调用服务端方法,遇到了java.net.ProtocolException: DELETE does not support writing
try {
url = new URL(path);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod(method);
OutputStreamWriter out = new OutputStreamWriter(
httpCon.getOutputStream());
out.write(new Gson().toJson(params));
out.close();
String urlStringsss = convertStreamToString(httpCon.getInputStream());
InfoPrinter.printLog(convertStreamToString(httpCon.getInputStream()));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
执行时捕捉到
java.net.ProtocolException: DELETE does not support writing
后来在万能的google帮助下,最终在stackoverflow上找到了答案,先来看国外的一位Coder怎么说
I do not believe that HTTP DELETE takes input - I believe it acts like a GET variant. The implementation provided by HTTP Client seems to support this conjecture as well. If you are looking to provide a delete with a body, you /might/ want to consider using a POST to a location that accepts a body. But in answer to your question, no, delete does not accept a body. You can add query parameters but not a body.
HTTP DELETE 不支持通过output来write参数,只能像GET方法一样通过url paramter来传递参数,否则会报标题上遇到的错误。