In this tutorial you will learn how to execute an HTTP DELETE request in Java. We use the HTTP DELETE request method to delete the specified resource.
You might also be interested to learn how to execute other HTTP methods. If you are, then please check the following tutorials as well:
To execute an HTTP request in Java, we need to have an HTTP client as a dependency. In this tutorial, we will cover the HTTP GET Request using the Apache HttpClient.
First, we need to add Maven dependency:
<dependency> <groupid>org.apache.httpcomponents</groupid> <artifactid>httpclient</artifactid> <version>4.5.13</version> </dependency>
Find other versions here → Apache HTTP Client. If you are not using Maven, you can also download JAR from the location above.
Execute an HTTP DELETE request in Java using Apache HttpClient
Below is a simple example of executing an HTTP DELETE request in Java.
import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import java.io.IOException; public class Test { public static void main(String[] args) throws IOException { try (CloseableHttpClient httpclient = HttpClients.createDefault()) { HttpDelete httpget = new HttpDelete("https://jsonplaceholder.typicode.com/todos/1"); System.out.println("Executing DELETE request..."); HttpResponse response = httpclient.execute(httpget); System.out.println("Status code: " + response.getStatusLine().getStatusCode()); String responseBody = new BasicResponseHandler().handleResponse(response); System.out.println("Response: " + responseBody); } } }
We also used the BasicResponseHandler to retrieve the response body.
Execute an HTTP DELETE request with HTTP headers
We can also add HTTP headers to the request, like in the following example:
import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import java.io.IOException; public class Test { public static void main(String[] args) throws IOException { try (CloseableHttpClient httpclient = HttpClients.createDefault()) { HttpUriRequest request = RequestBuilder.delete() .setUri("https://jsonplaceholder.typicode.com/todos/1") .setHeader(HttpHeaders.CONTENT_TYPE, "application/json") .setHeader("Authorization", "Bearer 123token") .build(); System.out.println("Executing DELETE request..."); HttpResponse response = httpclient.execute(request); System.out.println("Status code: " + response.getStatusLine().getStatusCode()); String responseString = new BasicResponseHandler().handleResponse(response); System.out.println("Response: " + responseString); } } }