How to send PUT, DELETE HTTP request in HttpURLConnection?

Matrix picture Matrix · Jun 26, 2009 · Viewed 262k times · Source

I want to know if it is possible to send PUT, DELETE request (practically) through java.net.HttpURLConnection to HTTP-based URL.

I have read so many articles describing that how to send GET, POST, TRACE, OPTIONS requests but I still haven't found any sample code which successfully performs PUT and DELETE requests.

Answer

Matthew Murdoch picture Matthew Murdoch · Jun 26, 2009

To perform an 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();

To perform an HTTP DELETE:

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