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

2022-08-31 07:57:12

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

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


答案 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();

答案 2

这就是它对我的工作方式:

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("DELETE");
int responseCode = connection.getResponseCode();

推荐