Send PUT, DELETE HTTP request in HttpURLConnection

manitaz picture manitaz · Nov 14, 2014 · Viewed 16.7k times · Source

I have created web service call using java below code. Now I need to make delete and put operations to be perform.

URL url = new URL("http://example.com/questions");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod( "POST" );
conn.setRequestProperty("Content-Type", "application/json");

OutputStream os = conn.getOutputStream();
os.write(jsonBody.getBytes());
os.flush();

When I add below code to perform DELETE action it gives errors saying:

java.net.ProtocolException: HTTP method DELETE doesn't support output.

conn.setRequestMethod( "DELETE" );

So how to perform delete and put requests?

Answer

Jamsheer picture Jamsheer · Nov 14, 2014

PUT example using HttpURLConnection:

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 example using HttpURLConnection:

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