Pular para o conteúdo principal

Testing the new Java 9 HTTP Client API on jShell

Java 9 is feature complete and one of the features is the new HTTP Client library, that will likely replace the existing HttpUrlConnection library. In this post you can read a few tests I made using this library.

The new HTTP API


To support HTTP 1 and 2, the new API brings 4 new main classes as you can see java.net.http package summary:
In this post we will focus ton HttpClient, HttpRequest and HttpResponse. Notice that the code I will show is slightly different from the one you see in the online javadocs  - the API is still in development and it is a subject to change!


Using HttpRequest, HttpResponse and HttpClient on jshell



JShell is awesome, you can run jshell binary that comes with Java 9 and start writing Java code. I recommend this article if you want to know more about it.

However, there's a small problem if you want to use the new API you must add the module java.httpclient. Yes, Java 9 has a modular system and not all modules are imported by default. See in HttpClient javadoc. In top left side you can see the module information. Some modules are not imported by default and you must start jshell with the --add-modules and I have an error when adding java.httpclient. I know it is a specific error for java.httpclient because it works with other modules, like java.logging. I also tried to specify the module path using --module-path  pointing to the jmods directory (because I see java.httpclient module there), but it was unsuccessful.


I found that the reason is the fact that the HttpClient  is on JDK incubator module jdk jdk.incubator.httpclient. The version I am using is build 9-ea+153.

[wsiqueir@wsiqueir jdk-9]$ ./bin/jshell --add-modules jdk.incubator.httpclient

Now I am ready to test the API using jshell! Just one thing to notice: The online HTTPClient documentation is not the same as in the version I showed above, we should trust the documentation that comes with the JDK bits!

Simple HTTP request



You need 3 lines of code to make an HTTP request. You could transform this in one liner code:

String body = HttpClient.newHttpClient().send(HttpRequest.newBuilder(URI.create("http://www.google.com")).GET().build(),  HttpResponse.BodyHandler.asString()).body()

mmmmm, better not.

Using Basic Authentication





I didn't like having to write a subclass of Authenticator just to set my credentials - that must be  better way to achieve this, but at least for now we know it works greatly!

Setting HTTP Headers


As you can see you can set HTTP headers when creating a new request. 

Conclusion

We tested the new Http Client API! I will stop here, but you can continue and test:

* Proxy configuration
* Use an executor
* SSL parameters


I saw all these methods on HttpClient and HttpBuilder methods - it is a full and modern Http client, guys! The only thing I didn't like is how we configure BASIC connection, but, as I mentioned, this code is a subject to change. Here's the code if you want to copy and paste it: 

// Basic request
import jdk.incubator.http.*;
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("http://www.google.com")).GET().build();
HttpResponse response = client.send(request, HttpResponse.BodyHandler.asString())
System.out.println(response.body())
--
// setting authentication
import jdk.incubator.http.*
public class MyAuthenticator extends Authenticator {
String usr = "kieserver";
char[] psw = "kieserver1!".toCharArray();
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(usr, psw);
}
}
URI uri = URI.create("http://localhost:8180/kie-server/services/rest/server")
HttpClient client = HttpClient.newBuilder().authenticator(new MyAuthenticator()).build();
HttpRequest request = HttpRequest.newBuilder(uri).GET().build()
HttpResponse response = client.send(request, HttpResponse.BodyHandler.asString())
System.out.println(response.body())
--
// setting http headers
HttpRequest request = HttpRequest.newBuilder(uri).header("Accept", "application/json").GET().build()
--
//one liner
String body = HttpClient.newHttpClient().send(
HttpRequest.newBuilder(URI.create("http://www.google.com")).GET().build(),
HttpResponse.BodyHandler.asString()
).body();

Comentários

Postagens mais visitadas deste blog

Genetic algorithms with Java

One of the most fascinating topics in computer science world is Artificial Intelligence . A subset of Artificial intelligence are the algorithms that were created inspired in the nature. In this group, we have Genetic Algorithms  (GA). Genetic Algorithms  To find out more about this topic I recommend the following MIT lecture and the Nature of Code book and videos created by Daniel Shiffman. Genetic Algorithms using Java After I remembered the basics about it, I wanted to practice, so I tried my own implementation, but I would have to write a lot of code to do what certainly others already did. So I started looking for Genetic Algorithm libraries and found Jenetics , which is a modern library that uses Java 8 concepts and APIs, and there's also JGAP . I decided to use Jenetics because the User Guide was so clear and it has no other dependency, but Java 8. The only thing I missed for Jenetics are more small examples like the ones I will show i...

Simplest JavaFX ComboBox autocomplete

Based on this Brazilian community post , I've created a sample Combobox auto complete. What it basically does is: When user type with the combobox selected, it will work on a temporary string to store the typed text; Each key typed leads to the combobox to be showed and updated If backspace is type, we update the filter Each key typed shows the combo box items, when the combobox is hidden, the filter is cleaned and the tooltip is hidden:   The class code and a sample application is below. I also added the source to my personal github , sent me PR to improve it and there are a lot of things to improve, like space and accents support.

Dancing lights with Arduino - The idea

I have been having fun with Arduino these days! In this article I am going to show how did I use an electret mic with Arduino to create a Dancing Lights circuit. Dancing Lights   I used to be an eletronician before starting the IT college. I had my own electronics maintenance office to fix television, radios, etc. In my free time I used to create electronic projects to sell and I made a few "reais" selling a version of Dancing lights, but it was too limited: it simply animated lamps using a relay in the output of a 4017 CMOS IC. The circuit was a decimal counter  controlled by a 555. 4017 decimal counter. Source in the image When I met Arduino a few years ago, I was skeptical because I said: I can do this with IC, why should I use a microcontroller. I thought that Arduino was for kids. But now my pride is gone and I am having a lot of fun with Arduino :-) The implementation of Dancing Lights with Arduino uses an electret mic to capture the sound and light leds...