我有一个Restful WebServices,我发送POST和GET HTTP请求,如何使用JAVA中的httpURLConection发送PUT和DELETE请求HTTP。
我有一个Restful WebServices,我发送POST和GET HTTP请求,如何使用JAVA中的httpURLConection发送PUT和DELETE请求HTTP。
放置
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();
}
}
java.net.ProtocolException: DELETE does not support writing
// httpURLConnection.setDoOutput(true);
protected void doPut(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException;
此方法不需要是“安全”或“幂等”的。通过PUT请求的操作可能具有用户可以承担责任的副作用。虽然不是必需的,但覆盖此方法的Servlet编写者可能希望将受影响的URI的副本保存在临时存储中。
protected void doDelete(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException