Delete resource
suggest changepublic static void delete (String urlString, String contentType) throws IOException {
HttpURLConnection connection = null;
try {
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setRequestMethod("DELETE");
connection.setRequestProperty("Content-Type", contentType);
Map<String, List<String>> responseHeader = connection.getHeaderFields();
StringBuilder sb = new StringBuilder();
Iterator<Map.Entry<String, List<String>>> iterator = responseHeader.entrySet().iterator();
while(iterator.hasNext())
{
Map.Entry<String, List<String>> entry = iterator.next();
sb.append(entry.getKey());
sb.append('=').append('"');
sb.append(entry.getValue());
sb.append('"');
if(iterator.hasNext())
{
sb.append(',').append(' ');
}
}
System.out.println(sb.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) connection.disconnect();
}
}
This will DELETE the resource in the specified URL, then print the response header.
How it works
- we obtain the
HttpURLConnectionfrom aURL. setRequestPropertysets theContent-Typeheader. This connection does not send that header unless the code sets it.setDoInput(true)tells the connection that we intend to use the URL connection for input.setRequestMethod("DELETE")to perform HTTP DELETE
At last we print the server response header.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents