Java Language HttpURLConnection Delete resource

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

   public 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>> map = connection.getHeaderFields();
            StringBuilder sb = new StringBuilder();
            Iterator<Map.Entry<String, String>> iterator = responseHeader.entrySet().iterator();
            while(iterator.hasNext())
            {
                Map.Entry<String, 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 HttpURLConnection from a URL.
  • Set the content type using setRequestProperty, by default it's application/x-www-form-urlencoded
  • 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.



Got any Java Language Question?