A response is more than its body. Before the body come the headers: lines of Name: value about the body, like the writing on an envelope around a letter. In Java, response.headers() holds them: firstValue("Content-Type") looks one up by name, and .get() takes its value out. The header Content-Type says what kind of body this is: text/html for a web page, application/json for JSON.
Requests carry headers too, and you can add your own: call .header(name, value) on the builder, before .build(). The Accept header tells the server which kind of answer you want. After the call, response.request().headers() are the headers your request carried. For example, to send an Accept-Language header that asks for French, and check that it went out:
HttpRequest frRequest = HttpRequest.newBuilder(URI.create(SUPPLIER + "/catalog")).header("Accept-Language", "fr").build();
HttpResponse<String> reply = client.send(frRequest, HttpResponse.BodyHandlers.ofString());
System.out.println(reply.request().headers().firstValue("Accept-Language").get());
An Accept of */* means anything will do. Your script asks for two paths and prints what their headers say:
GET / → Content-Type: text/html; charset=utf-8 GET /prices (Accept: application/json) → Content-Type: application/json
Body: Supplier API. Try /prices Content-Type: text/html; charset=utf-8 Sent Accept: application/json Got Content-Type: application/json
Your task: the starting code asks for the home page and prints its body. Print its Content-Type. Then ask for /prices with an Accept header for JSON, and print the Accept header that went out and the Content-Type that came back.
Assignment
Follow the Coding Tutorial to read the Content-Type of two answers and send an Accept header of your own.
Hintresponse.headers() are the headers that came back; response.request().headers() are the ones that went out. Read both with firstValue(name).get(). For the second request, request and response already exist, so leave out the type in front.
Free plan: 30 tutor messages. PRO is unlimited.
