我想知道是否可以通过java.net.HttpURLConnection向基于HTTP的URL发送PUT,DELETE请求(实际上)。

我已经读过很多描述如何发送GET,POST,TRACE,OPTIONS请求的文章,但是我仍然没有找到成功执行PUT和DELETE请求的示例代码。

最佳答案

要执行HTTP PUT:

URL url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(
    httpCon.getOutputStream());
out.write("Resource content");
out.close();
httpCon.getInputStream();

要执行HTTP删除:
URL url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestProperty(
    "Content-Type", "application/x-www-form-urlencoded" );
httpCon.setRequestMethod("DELETE");
httpCon.connect();

07-27 13:50