143

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.

Sam
  • 7,252
  • 16
  • 46
  • 65
Matrix
  • 7,477
  • 14
  • 66
  • 97

8 Answers8

188

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();
Adam
  • 191
  • 1
  • 2
  • 14
Matthew Murdoch
  • 30,874
  • 30
  • 96
  • 127
  • 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 Jun 27 '09 at 21:59
  • or Is it possible to send image/video/audio to server using POST method? – Matrix Jun 27 '09 at 22:08
  • 1
    Yes. All these things are possible but really depend on the API supported by your mail/blog provider. – Matthew Murdoch Jun 28 '09 at 20:08
  • 6
    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 :-) – ryskajakub Jul 26 '10 at 23:10
  • 8
    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 Aug 20 '10 at 18:39
  • @Eric: Exactly, this is the case. – Diego Sevilla Nov 27 '10 at 01:27
  • @Matthew, please add httpCon.getInputStream() to the examples – Adrian Mouat Jan 11 '11 at 10:21
  • please open up this article, hope this might help you all... http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html#d5e43 – gumuruh May 08 '12 at 18:02
  • 3
    I got " java.net.ProtocolException: DELETE does not support writing " – Kimo_do Apr 04 '13 at 15:57
  • for delete should we specify which data to be deleted ? like "username":"abc" ? – Anonymous Apr 25 '13 at 03:19
  • 1
    @edisusanto the named resource (indicated by the URL) is the data which will be deleted. – Matthew Murdoch Apr 25 '13 at 06:09
  • @Matthew i've got the same error as Kimo_do which is `java.net.ProtocalException: DELETE does not support writing' .. – Anonymous Apr 26 '13 at 04:41
  • @edisusanto which line of code is throwing the `ProtocolException`? – Matthew Murdoch Apr 26 '13 at 09:09
  • Just a quick improvement on the delete code, it should look like this in order to work properly: `URL url = new URL("http://www.example.com/resource"); HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); httpCon.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded" ); httpCon.setRequestMethod("DELETE"); httpCon.connect(); httpCon.getInputStream();` – BreadicalMD Mar 18 '14 at 16:43
  • `httpCon.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded" )` is not necessary, only for errornous server implementations. – hgoebl Dec 20 '14 at 16:32
  • 1
    `httpCon.setDoOutput(true);` does not work on `delete()` operation. – Darpan Aug 14 '15 at 12:06
  • Okay if I want to test the application by passing URL in the browser as `http://localhost:8080/spring-jpa/products?id=1` , how to differentiate them whether they are `GET`, `PUT`, or `DELETE` – viper May 19 '16 at 11:50
  • @MatthewMurdoch can you help me to solve this question, I got it while trying out your code for my task [http://stackoverflow.com/questions/41670608/how-to-call-the-github-api-form-httpsurlconnection-in-java?noredirect=1#comment70539532_41670608] – Kasun Siyambalapitiya Jan 16 '17 at 08:08
  • @MatthewMurdoch can this method be used to pass parameters for the APIs like github API – Kasun Siyambalapitiya Jan 16 '17 at 08:43
  • For PUT request, the InputStream returned by getInputStream is never closed. Is it OK? – Vladimir Makhnovsky Jan 23 '20 at 20:12
26

This is how it worked for me:

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("DELETE");
int responseCode = connection.getResponseCode();
Eli Heifetz
  • 260
  • 3
  • 4
13
public  HttpURLConnection getHttpConnection(String url, String type){
        URL uri = null;
        HttpURLConnection con = null;
        try{
            uri = new URL(url);
            con = (HttpURLConnection) uri.openConnection();
            con.setRequestMethod(type); //type: POST, PUT, DELETE, GET
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setConnectTimeout(60000); //60 secs
            con.setReadTimeout(60000); //60 secs
            con.setRequestProperty("Accept-Encoding", "Your Encoding");
            con.setRequestProperty("Content-Type", "Your Encoding");
        }catch(Exception e){
            logger.info( "connection i/o failed" );
        }
        return con;
}

Then in your code :

public void yourmethod(String url, String type, String reqbody){
    HttpURLConnection con = null;
    String result = null;
    try {
        con = conUtil.getHttpConnection( url , type);
    //you can add any request body here if you want to post
         if( reqbody != null){  
                con.setDoInput(true);
                con.setDoOutput(true);
                DataOutputStream out = new  DataOutputStream(con.getOutputStream());
                out.writeBytes(reqbody);
                out.flush();
                out.close();
            }
        con.connect();
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String temp = null;
        StringBuilder sb = new StringBuilder();
        while((temp = in.readLine()) != null){
            sb.append(temp).append(" ");
        }
        result = sb.toString();
        in.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        logger.error(e.getMessage());
    }
//result is the response you get from the remote side
}
stackFan
  • 1,528
  • 15
  • 22
12

I agree with @adietisheim and the rest of people that suggest HttpClient.

I spent time trying to make a simple call to rest service with HttpURLConnection and it hadn't convinced me and after that I tried with HttpClient and it was really more easy, understandable and nice.

An example of code to make a put http call is as follows:

DefaultHttpClient httpClient = new DefaultHttpClient();

HttpPut putRequest = new HttpPut(URI);

StringEntity input = new StringEntity(XML);
input.setContentType(CONTENT_TYPE);

putRequest.setEntity(input);
HttpResponse response = httpClient.execute(putRequest);
Alvaro
  • 465
  • 5
  • 10
  • Just wanted to say thank you for this. Spent many hours trying to get my code using `HttpURLConnection` to work, but kept running into an odd error, specifically: `cannot retry due to server authentication, in streaming mode`. Following your advice worked for me. I realize this does not exactly answer the question, which asks to use `HttpURLConnection`, but your answer helped me. – Tom Catullo Nov 01 '16 at 21:44
  • @Deprecated use HttpClientBuilder instead – Waldemar Wosiński Aug 10 '17 at 14:54
4

For doing a PUT in HTML correctly, you will have to surround it with try/catch:

try {
    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();
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (ProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
4

UrlConnection is an awkward API to work with. HttpClient is by far the better API and it'll spare you from loosing time searching how to achieve certain things like this stackoverflow question illustrates perfectly. I write this after having used the jdk HttpUrlConnection in several REST clients. Furthermore when it comes to scalability features (like threadpools, connection pools etc.) HttpClient is superior

adietisheim
  • 3,434
  • 1
  • 19
  • 14
2

Even Rest Template can be an option :

String payload = "<?xml version=\"1.0\" encoding=\"UTF-8\"?<RequestDAO>....";
    RestTemplate rest = new RestTemplate();

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/xml");
    headers.add("Accept", "*/*");
    HttpEntity<String> requestEntity = new HttpEntity<String>(payload, headers);
    ResponseEntity<String> responseEntity =
            rest.exchange(url, HttpMethod.PUT, requestEntity, String.class);

     responseEntity.getBody().toString();
Gloria Rampur
  • 353
  • 3
  • 12
0

there is a simple way for delete and put request, you can simply do it by adding a "_method" parameter to your post request and write "PUT" or "DELETE" for its value!

Vineeth Sai
  • 3,389
  • 7
  • 23
  • 34
Mohamad Rostami
  • 420
  • 3
  • 17