How to send PUT, DELETE HTTP request in HttpURLConnection?
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:
DELETE 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
setConnectTimeoutandsetReadTimeout. - Exception management: Always use
try-catchfor network operations. - Connection cleanup: Always
disconnect()theHttpURLConnectioninstance in afinallyblock.
The HttpClient Alternative
HttpURLConnection is not the only player in town! Overcome limitations using the more scalable and more user-friendly HttpClient:
- Resource management:
HttpClienthandles thread & connection pools masterfully. - Ease of use:
HttpClientsimplifies HTTP operations and responses handling.
Example of PUT request with HttpClient:
Example of DELETE request with HttpClient:
Proper response handling
Ensure you check the response code to verify whether your request was successful:
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
OutputStreamWriterto write your data toconn.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.
Was this article helpful?