HTTP DELETE With Request Body
HTTP DELETE is typically used to request the deletion of a resource from a server. However, unlike other HTTP methods like POST or PUT, the DELETE method doesn’t natively support a request body. Despite this limitation, some APIs require sending a body with a DELETE request, especially when dealing with complex data that needs to be passed to the server. Let us delve into understanding how a Java HTTP DELETE request body works and how it can be effectively implemented in various HTTP client libraries.
1. Spring’s RestTemplate
Spring’s RestTemplate is a synchronous HTTP client used to interact with RESTful services. Although HTTP DELETE doesn’t support a body by default, we can work around this by using the HttpEntity
to send a body with the DELETE request.
1.1 Code Example: Using Spring RestTemplate
import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; public class DeleteRequestExample { public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); // API URL String url = "https://example.com/api/resource"; // Create request headers HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", "Bearer <your_token>"); // Request body (e.g., JSON data) String body = "{\"id\": 123}"; // Create HttpEntity with body and headers HttpEntity<String> entity = new HttpEntity<>(body, headers); // Send DELETE request with body ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.DELETE, entity, String.class); // Print response System.out.println("Response: " + response.getBody()); } }
1.1.1 Code Explanation and Output
This Java program demonstrates how to send an HTTP DELETE request with a request body using Spring’s RestTemplate
. The main
method starts by creating an instance of RestTemplate
, which is used to perform HTTP operations in a Spring application.
The target API endpoint is defined as a URL: https://example.com/api/resource
. Next, an HttpHeaders
object is created to include necessary headers for the request. In this example, an Authorization header is set with a bearer token ("Bearer <your_token>"
), which is commonly used for authenticated API calls.
The body of the DELETE request is specified as a JSON string: "{\"id\": 123}"
. This body contains the ID of the resource to be deleted. Both the request body and headers are wrapped in an HttpEntity
object, which acts as a container for the HTTP request’s metadata.
The actual HTTP DELETE request is executed using the exchange
method of the RestTemplate
. This method takes the URL, the HTTP method (DELETE in this case), the HttpEntity
containing the body and headers, and the response type (String.class
) as arguments.
Finally, the response from the server is printed to the console using System.out.println
. This response typically contains confirmation that the resource has been deleted or any error message if the operation failed.
This example highlights how RestTemplate
provides flexibility for sending HTTP requests with custom headers and a body, even for methods like DELETE, which do not traditionally support a request body.
When executed, the code produces the following output in the IDE console.
Response: Resource deleted successfully
2. Code Using Apache HTTP 4
Apache HttpClient is another popular library for making HTTP requests in Java. It provides more low-level control over the request and allows you to handle the DELETE request with a body as well.
2.1 Code Example: Using Apache HttpClient 4
import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.client.methods.HttpDelete; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpResponse; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class ApacheDeleteRequestExample { public static void main(String[] args) throws Exception { String url = "https://example.com/api/resource"; // Create HTTP client CloseableHttpClient client = HttpClients.createDefault(); // Create DELETE request with body HttpDeleteWithBody delete = new HttpDeleteWithBody(url); delete.setEntity(new StringEntity("{\"id\": 123}")); delete.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); delete.setHeader("Authorization", "Bearer "); // Execute the request try (CloseableHttpResponse response = client.execute(delete)) { HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity); System.out.println("Response: " + result); } } // Custom class to handle DELETE with a body public static class HttpDeleteWithBody extends HttpDelete { public HttpDeleteWithBody(String uri) { super(uri); } @Override public String getMethod() { return "DELETE"; } } }
2.1.1 Code Explanation and Output
This Java program demonstrates how to send an HTTP DELETE request with a request body using Apache HttpClient. The program starts by defining the target API URL: https://example.com/api/resource
. A CloseableHttpClient
instance is created using HttpClients.createDefault()
, which provides a default implementation of the HTTP client.
Since the standard HttpDelete
class in Apache HttpClient does not support request bodies, the program defines a custom class, HttpDeleteWithBody
, extending HttpDelete
. This custom class overrides the getMethod()
method to ensure that the HTTP DELETE method is still used, even when a body is included.
An instance of HttpDeleteWithBody
is created with the API URL. A JSON string, "{\"id\": 123}"
, is set as the request body using StringEntity
. Additional headers are added to the request, including Content-Type
set to application/json
and an Authorization header containing a bearer token ("Bearer <your_token>"
).
The DELETE request is executed using the execute
method of the CloseableHttpClient
. The response is captured as a CloseableHttpResponse
, and its entity is retrieved to extract the response body. The response content is then converted to a string using EntityUtils.toString()
and printed to the console.
This example showcases how to customize Apache HttpClient to handle DELETE requests with a request body, a functionality not directly supported by the standard HttpDelete
class. The use of a custom class allows greater flexibility when interacting with APIs that require this behavior.
When executed, the code produces the following output in the IDE console.
Response: Resource deleted successfully
3. Comparison
Aspect | Spring RestTemplate | Apache HttpClient |
---|---|---|
Overview | A high-level, synchronous HTTP client provided by Spring for interacting with RESTful APIs. It abstracts HTTP communication details. | A low-level HTTP client library designed for building and executing HTTP requests with more control over configurations. |
Ease of Use | Simple and developer-friendly with built-in support for handling common tasks like JSON serialization and deserialization. | Requires more configuration and coding effort, making it less straightforward but highly customizable. |
Flexibility | Provides limited flexibility as it abstracts much of the HTTP layer. Ideal for quick and standard REST API calls. | Offers granular control over requests and responses, including custom headers, retries, and connection pooling. |
Built-in Features | Supports object mapping with Jackson, query parameters, form data, and handling exceptions like HttpClientErrorException . | Supports advanced features like connection reuse, request retries, and fine-grained configuration of timeouts and proxy settings. |
Thread Safety | Typically used as a single instance (bean) in a Spring context, making it safe for concurrent use. | Custom configurations like connection pooling ensure thread safety when properly managed. |
Learning Curve | Lower learning curve due to Spring’s abstraction and integration with its ecosystem. | Higher learning curve due to its low-level nature and the need for additional setup. |
Preferred Use Cases | Best for quick integrations with REST APIs in Spring applications where simplicity is valued over fine-grained control. | Ideal for scenarios requiring advanced HTTP configuration, such as custom authentication, connection pooling, or performance optimization. |
Dependency | Requires Spring Framework dependencies. | Requires Apache HttpClient library dependencies. |
Which is better? | If you’re working within the Spring ecosystem and need a simple, straightforward solution for making HTTP requests, Spring RestTemplate is the better choice. | If you require more control over your HTTP requests, such as managing custom headers, connection pooling, or optimizing performance, Apache HttpClient is the better option. |
4. Conclusion
While HTTP DELETE does not traditionally support request bodies, both Spring RestTemplate and Apache HttpClient provide ways to work around this limitation. By using HttpEntity
in Spring and customizing the HttpDelete
class in Apache HttpClient, we can successfully send a DELETE request with a body.
It’s important to note that not all servers or APIs may accept a body with a DELETE request, so always refer to the API documentation before implementing it in production. However, these solutions are useful when working with APIs that support it.