Start learning free

LESSON 1 OF 173 · BACKEND: HOW THE WEB WORKS

Your First Request in Java

Practice

Every time a browser opens a page, it sends a request to a server, a program waiting on some computer, and the server sends back a response. A Java program can do the same with the HttpClient built into Java, in java.net.http.

An HttpClient sends requests. An HttpRequest says what to ask for, and client.send(...) sends it and returns an HttpResponse. A response starts with a status code, a number that says how it went (200 means OK), and then comes the body, the content itself. .statusCode() gives the number, and .body() gives the body as a String.

HttpClient client = HttpClient.newHttpClient();
HttpRequest about = HttpRequest.newBuilder(URI.create("https://example.com/about")).build();
HttpResponse<String> page = client.send(about, HttpResponse.BodyHandlers.ofString());
System.out.println(page.statusCode());
System.out.println(page.body());

The shop's supplier runs a server at the address in SUPPLIER. Its home page is the path /. When your program asks for it, it must print:

Status: 200
Text: Supplier API. Try /prices

Your task: make a client, build a GET request for the supplier's home page, send it and keep the answer in response, then print its status code and its body, each after its label.


Assignment
Follow the Coding Tutorial to send your first request and print the status code and the body that come back.


Hint
The address is a string: join SUPPLIER and "/" with +. System.out.println takes one string, so join each label and its value with + too.


STEP 1 OF 5
    Ctrl + Enter to check

    Web First Request in Java

    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free