小编典典

如何在HttpURLConnection中发送PUT,DELETE HTTP请求?

java

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

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


阅读 704

收藏
2020-03-17

共1个答案

小编典典

要执行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();
2020-03-17