Friday, November 1, 2013

How to send DELETE HTTP request in HttpURLConnection java

In a DELETE request, the parameters are sent as part of the URL and you can not send request body.
This code should get you started:

String urlParameters = "param1=1&param2=2";
String request = "http://api.server.com";
URL url = new URL(request + "?" + urlParameters); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("DELETE"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset", "utf-8");
connection.setUseCaches (false);

Print out response code and get response from server:


System.out.println("Response code: " + connection.getResponseCode());

BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line, responseText = "";
while ((line = br.readLine()) != null) {
    System.out.println("LINE: "+line);
    responseText += line;
}
br.close();
connection.disconnect();

No comments:

Post a Comment