Java 11+
Prerequisites
You should have a running environment for Java 11 (or later) ready set up. Check your installation by printing the version.
(base) ~ % java -version
openjdk version "11.0.10" 2021-01-19
OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.10+9)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.10+9, mixed mode)
Plain request
Within Java 11 there (finally) is a pretty plain HttpClient on board, so we can just jump in to the JShell, import the needed classes and fire up our request
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.BodyHandlers;
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.football-data.org/v4/competitions"))
.build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());
Adding a header to pass the authentication for other resources to use is easy. Use the code below to add authentication to be able to use a restricted resource:
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.football-data.org/v4/competitions/PL/matches?matchday=28"))
.header("X-Auth-Token", "UR_TOKEN")
.build();