Explain Codes LogoExplain Codes Logo

How to send PUT, DELETE HTTP request in HttpURLConnection?

java
httpclient
http-requests
best-practices
Alex KataevbyAlex KataevยทFeb 21, 2025
โšกTLDR

To execute PUT or DELETE requests with Java's HttpURLConnection, utilize the setRequestMethod("PUT") or setRequestMethod("DELETE"). Here's a fast-track example for both:

PUT request:

HttpURLConnection conn = (HttpURLConnection) new URL("http://example.com/resource").openConnection(); conn.setRequestMethod("PUT"); // Sending a PUT request conn.setDoOutput(true); // For sending data OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write("data=example"); // Replace with your data (Remember, 'PUT' an effort into your data! ๐Ÿ˜‰) writer.close(); // Always practice closing! The environment will thank you! conn.getInputStream(); // To trigger the request

DELETE request:

HttpURLConnection conn = (HttpURLConnection) new URL("http://example.com/resource").openConnection(); conn.setRequestMethod("DELETE"); // Sending a DELETE request (It's DELETE-icious! ๐Ÿ˜„) conn.getInputStream(); // To trigger the request

Remember to handle exceptions gracefully and close the connection after you're done.

Comprehending HTTP requests: A detailed guide

Handling HttpURLConnection can be a stroll in the park if you know what you're doing. Master the best practices and understand alternative approaches to write prom & efficient code!

HttpURLConnection: The golden rules

Follow these practices to ensure your code is as robust as a Swiss watch! โŒš

  • Set timeouts: Define limits using setConnectTimeout and setReadTimeout.
  • Exception management: Always use try-catch for network operations.
  • Connection cleanup: Always disconnect() the HttpURLConnection instance in a finally block.

The HttpClient Alternative

HttpURLConnection is not the only player in town! Overcome limitations using the more scalable and more user-friendly HttpClient:

  • Resource management: HttpClient handles thread & connection pools masterfully.
  • Ease of use: HttpClient simplifies HTTP operations and responses handling.

Example of PUT request with HttpClient:

var client = HttpClient.newHttpClient(); var request = HttpRequest.newBuilder() .uri(URI.create("http://example.com/resource")) .PUT(HttpRequest.BodyPublishers.ofString("data=example")) // Insert your data here .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); // Fire it off!

Example of DELETE request with HttpClient:

var client = HttpClient.newHttpClient(); var request = HttpRequest.newBuilder() .uri(URI.create("http://example.com/resource")) .DELETE() // The DELETE-er of Worlds begins here! ๐Ÿ˜ˆ .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); // Fire!

Proper response handling

Ensure you check the response code to verify whether your request was successful:

int statusCode = conn.getResponseCode(); if (statusCode == HttpURLConnection.HTTP_OK) { // Success! You can relax now, perhaps with a drink? โ˜• } else { // Failure! Time to debug, buddy! ๐Ÿž }

For HttpClient, you can examine response.statusCode() similarly.

Key procedures: Handling request content and headers

When making PUT requests, you usually need to send additional content:

  • Set ContentType Header: Use conn.setRequestProperty("Content-Type", "your_content_type"); to let the server know the type of data coming in.
  • Write Data: Use OutputStreamWriter to write your data to conn.getOutputStream(). But remember, always close the writer to prevent resource leaks (just like saving water! ๐Ÿ’ฆ).

For DELETE requests, headers might seem optional. But if it's required:

  • Set Initial Headers: Just as with PUT, set any required headers using conn.setRequestProperty.