Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send PUT, DELETE HTTP request in HttpURLConnection in JAVA

I have Restful WebServices, and i send POST and GET HTTP request, how to send PUT and DELTE request HTTP in httpURLConection with JAVA.

like image 997
user2816207 Avatar asked Oct 11 '13 14:10

user2816207


2 Answers

PUT

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

DELETE

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();
    }
} 
like image 135
bmlynarczyk Avatar answered Oct 21 '22 15:10

bmlynarczyk


If I use the DELETE request from @BartekM, it get this exception:

 java.net.ProtocolException: DELETE does not support writing

To fix it, I just remove this instruction:

 // httpURLConnection.setDoOutput(true);

source: Sending HTTP DELETE request in Android

like image 37
spritus Avatar answered Oct 21 '22 13:10

spritus