views:

6039

answers:

3

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 request but still not finding any sample code which successfully perform PUT and DELETE request. Can any one give idea regarding that?

+1  A: 

I would recommend Apache HTTPClient.

Clint
+3  A: 

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

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();
Matthew Murdoch
So is it possible that using java code you can delete mail from your mail account(using DELETE method) or Using post method you can create document(say like blogs.) ?
Matrix
or Is it possible to send image/video/audio to server using POST method?
Matrix
Yes. All these things are possible but really depend on the API supported by your mail/blog provider.
Matthew Murdoch
hello, I'm having troubles with the `delete`. When I run this code as it is here, nothing really happens, the request is not sent. Same situation is when I am doing `post` requests, but there I can use for example `httpCon.getContent()` which triggers the request. But the `httpCon.connect()` doesn't trigger anything in my machine :-)
coubeatczech
In the examples above, I believe that you'll need to call httpCon.getInputStream() at the end to cause the request to actually be sent.
Eric Smith
A: 

It is possible to send content (Output stream) with HTTP DELETE request?

Vitaliy
Hi, welcome at Stackoverflow! This is a Q)
BalusC