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

我有Restful WebServices,我发送POST和GET HTTP请求,如何使用JAVA在httpURLConection中发送PUT和DELTE请求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(); } } 

如果我使用@BartekM的DELETE请求,它会得到以下exception:

  java.net.ProtocolException: DELETE does not support writing 

要修复它,我只是删除此指令:

  // httpURLConnection.setDoOutput(true); 

source: 在Android中发送HTTP DELETE请求

你可以覆盖

 protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException; 

执行HTTP PUT操作; 默认实现报告HTTP BAD_REQUEST错误。 PUT操作类似于通过FTP发送文件。 覆盖此方法的Servlet编写器必须遵守随请求一起发送的任何Content- *标头。 (这些标题包括内容长度,内容类型,内容传输编码,内容编码,内容基础,内容语言,内容位置,内容-MD5和内容范围。)如果子类不能遵守内容标题,然后它必须发出错误响应(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的副本保存在临时存储中。