I am building a microservice and need to send a JSON payload to a remote REST API. I want to avoid adding heavy external libraries like Apache HttpClient or OkHttp if possible. What is the standard way to perform a POST request using the built-in Java 11+ HttpClient? Specifically, how do I set the "Content-Type" to "application/json" and handle the response body effectively? Are there any common pitfalls regarding timeouts or SSL certificates that I should be aware of?
3 answers
Since the release of Java 11, the java.net.http.HttpClient has become the preferred way to handle web requests. It is much more readable than the older HttpURLConnection. To send a POST, you create a HttpRequest using the .POST(BodyPublishers.ofString(json)) method. You must explicitly add a .header("Content-Type", "application/json") to ensure the server parses your data correctly. One major advantage of this new client is that it supports asynchronous requests natively using sendAsync, which is great for performance. Just remember to handle the InterruptedException and IOException that the synchronous send method might throw during the network handshake.
Have you looked into how the newer HttpClient handles connection pooling and redirection? If your API requires a redirect after the POST (like a 302 status code), do you know if you need to manually configure the .followRedirects(HttpClient.Redirect.NORMAL) builder option, or does it do that by default?
If you are stuck on an older version like Java 8, you'll have to use HttpURLConnection. It's a bit verbose because you have to manually write to the OutputStream, but it gets the job done without external jars.
Susan is right, but I strongly suggest upgrading to Java 11+. The code is nearly 50% shorter and much easier to maintain for enterprise-level software development projects.
William, that is a crucial point! By default, the HttpClient does not follow redirects. You have to specify it in the builder. Also, regarding the POST request, make sure to set a timeout using .timeout(Duration.ofSeconds(10)). Without a defined timeout, your application might hang indefinitely if the server is unresponsive, which is a common cause of memory leaks in production environments. I learned that the hard way while working on a payment gateway integration last year!