English English

Java 13 - HTTP Client API: Daten abrufen von und senden an einem Webserver

Java 11 introduced the new HTTP Client API which can be used to create HTTP responses and requests through Java code. This is an introduction to the usage of this new API in Java 13.


You need to import the package "java.net.http" to use the HTTP Client API. This package is available in Java 11+.


Why should you use the new HTTP Client API?

-) It support HTTP/2
-) It can send data asynchron or synchron
-) New functions e.g. sending data automatically without client request


Main classes and interfaces of the HTTP Client API

-) "HttpClient" class: Saves configuration information and is used to send HTTP requests and retrieve HTTP responses.
-) "HttpRequest" class: Saves the HTTP request information that will be sent to the HTTP server
-) "HttpResponse" interface: A HTTP response which you get from the HTTP server after you send your HTTP request. This contains data that you have requested from the HTTP server in your HTTP request.
-) "WebSocket" interface: To represent a WebSocket client. Used to create a peer to peer connection between a client and a server.

But this introduction will show how a HttpClient and HttpRequest object is created and used.


Creating a HttpClient object

-) "newHttpClient()": This function creates a HttpClient in default settings which includes the "GET" request.
-) "sendAsync()": Sends the request data asynchronously. This function returns an object of the class "CompletableFuture<HttpResponse<T>>". This object will have the HTTP response data from the HTTP server where we did sent our HTTP request.
-) "send()": Sends the request data normally.

The creation of a HttpRequest object are and how to handle the data of the HttpResponse must be set in both the functions "send()" and "sendAsync()" as well.
There are of course more functions available for a HttpClient object. This were the most important functions.

Example of an HttpClient:

.sendAsync(HttpRequest.newBuilder().uri(URI.create("http://MY-SERVER.tld")).build(), BodyHandlers.ofString())

What this example does: Fetch and display data (from the HTTP body) line for line from the website "http://MY-SERVER.tld".
The HTTP response data is converted to a string by calling the function "BodyHandler.ofString()". The function "thenApply()" calls a function (here: the body is retrieved from the HTTP reponse) when the HTTP server sent a HTTP response.
The function "thenAccept()" can be used to display data from the here created data flow.


Creating a HttpRequest object

-) "newBuilder()": This function builds a new HttpRequest object.
-) "build()": This function is called at the end the creation of the HttpRequest object.

Example of an HttpRequest object:


This creates an HTTP "POST" request that can contain data. Here we send a string with the content "username=JohnDoe") that consists of a user's username and password.


Now, lets have a look on example on how to use these to fetch and use data from another web server.


Usage example

// Fetch and load currencies and country names
		HttpClient client = HttpClient.newHttpClient();
	    Map<String, String> currencies = new TreeMap<>();
	    List<String> countries = new ArrayList<>();

		String urlJsonFile = "https://raw.githubusercontent.com/lorey/list-of-countries/master/csv/countries.csv";
		try {
			Path downloadPath = Paths.get("countries.csv");
			HttpRequest request = HttpRequest.newBuilder().uri(URI.create(urlJsonFile))
					.header("Accept", "application/csv").build();
			HttpResponse<Path> response = client.send(request,
			// Get saved csv file
			Path filePath = response.body();

			BufferedReader csvReader = new BufferedReader(new FileReader(filePath.toFile()));
			String line = null;
			String[] lineArray;
			do {
				if (line != null) {
					line = csvReader.readLine();
					lineArray = line.split(";");
					currencies.put(lineArray[5], lineArray[6]);
			} while (line != null);

		} catch (IOException | InterruptedException e) {
			System.out.println("" + e);

This code downloads an CSV file from a github repository (https://github.com/lorey/list-of-countries) into the project folder, parses countries and currencies and saves these in respective objects (a "List" and "Map").


More about the HTTP package:


Cookies erleichtern die Bereitstellung unserer Dienste. Mit der Nutzung unserer Dienste erklären Sie sich damit einverstanden, dass wir Cookies verwenden.