我有 Restful WebServices,我发送 POST 和 GET HTTP 请求,如何使用 JAVA 在 httpURLConection 中发送 PUT 和 DELTE 请求 HTTP。
3 回答
放
URL url = null;
try {
url = new URL("http://localhost:8080/putservice");
} catch (MalformedURLException exception) {
exception.printStackTrace();
}
HttpURLConnection httpURLConnection = null;
DataOutputStream dataOutputStream = null;
try {
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestMethod("PUT");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
dataOutputStream.write("hello");
} catch (IOException exception) {
exception.printStackTrace();
} finally {
if (dataOutputStream != null) {
try {
dataOutputStream.flush();
dataOutputStream.close();
} catch (IOException exception) {
exception.printStackTrace();
}
}
if (httpsURLConnection != null) {
httpsURLConnection.disconnect();
}
}
删除
URL url = null;
try {
url = new URL("http://localhost:8080/deleteservice");
} catch (MalformedURLException exception) {
exception.printStackTrace();
}
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
httpURLConnection.setRequestMethod("DELETE");
System.out.println(httpURLConnection.getResponseCode());
} catch (IOException exception) {
exception.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
如果我使用来自@BartekM 的 DELETE 请求,它会收到以下异常:
java.net.ProtocolException: DELETE does not support writing
要修复它,我只需删除此指令:
// httpURLConnection.setDoOutput(true);
你可以覆盖
protected void doPut(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException;
执行 HTTP PUT 操作;默认实现报告 HTTP BAD_REQUEST 错误。PUT 操作类似于通过 FTP 发送文件。覆盖此方法的 Servlet 编写者必须遵守随请求发送的任何 Content-* 标头。(这些标头包括 content-length、content-type、content-transfer-encoding、content-encoding、content-base、content-language、content-location、content-MD5 和 content-range。)如果子类不能接受内容头,然后它必须发出错误响应(501)并丢弃请求。有关详细信息,请参阅 HTTP 1.1 RFC。
此方法不需要是“安全的”或“幂等的”。通过 PUT 请求的操作可能会产生副作用,用户需要对此负责。尽管不是必需的,但覆盖此方法的 servlet 编写者可能希望将受影响的 URI 的副本保存在临时存储中。
和
protected void doDelete(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException
执行 HTTP DELETE 操作;默认实现报告 HTTP BAD_REQUEST 错误。DELETE 操作允许客户端请求从服务器中删除 URI。此方法不需要是“安全的”或“幂等的”。通过 DELETE 请求的操作可能会产生副作用,用户可能需要为此负责。尽管不是必需的,但继承此方法的 servlet 编写者可能希望将受影响的 URI 的副本保存在临时存储中。