If you need to do more complex requests with bodies POST, or customize timeouts or such, you can, but I've never really found this API to be intuitive. So when should you use it HTTPUrlConnection ? If you are supporting clients using older versions of Java and you can't add a dependency, this may be your best solution.
I suspect this will only affect a small minority of developers, but you may encounter it in older codebases. For more modern approaches, read on. Java 11 HttpClient More than twenty years later HttpURLConnection, and while Black Panther was on the screens, a new HTTP client was added to Java 11: java.
net.http.HttpClient. Featuring a much more logical API, it is able philippines mobile number example to handle the HTTP/2 protocol and WebSockets.
It also allows requests to be made synchronously or asynchronously using the API CompletableFuture. 99% of the time when I make an HTTP request I want to be able to read the body of the response in my code. Any library that makes this task complex is not going to do it for me. HttpClient accepts a BodyHandler to convert an HTTP response to a class of your choice.
String, byte[] for binary data, Stream<String> which splits by lines, and a few others.
You can also define your own, which can be useful since there is no built-in BodyHandler to parse JSON. I wrote one ( here ) based on Jackson following an example from Java Docs . It returns a Supplier for the APOD class , which allows you to call it .
get() when you need the result. This is a synchronous request: Java Copy the code // create a client var client = HttpClient.newHttpClient(); // create a request var request = HttpRequest.newBuilder( URI.creat od?api_key=DEMO_KEY")) .header("accept", "application/json") .build(); // use the client to send the request var response = client.
send(request, new JsonBodyHandler<>(APOD.class)); // the response: System.
out.println(response.body().get().title); For an asynchronous request, the client and request are done the same way, and then you just need to call .sendAsync instead of .send : Java Copy the code // use the client to send the request var responseFuture = client.sendAsync(request, new
There are a few built-in handlers:
-
- Posts: 9
- Joined: Sun Dec 22, 2024 4:39 am