Sub topic 6
Sending a request with send
This chapter assumes you can build an HttpClient and an HttpRequest, and that you know how BodyHandlers choose the response type. It also assumes you are comfortable with checked exceptions. Here you will look at what send does, what it returns, and how it fails.
What send does
HttpClient.send is the synchronous way to run a request. The calling thread blocks until the response is available, then gets an HttpResponse<T> back. The signature is:
<T> HttpResponse<T> send(HttpRequest request,
HttpResponse.BodyHandler<T> responseBodyHandler)
throws IOException, InterruptedExceptionThe type parameter T comes from the body handler you pass, not from the request. The same request can produce a String, a byte[], a Path or an InputStream depending on the handler.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Path;
import java.time.Duration;
public class SendTypes {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com/"))
.timeout(Duration.ofSeconds(10))
.GET()
.build();
HttpResponse<String> asText =
client.send(request, HttpResponse.BodyHandlers.ofString());
HttpResponse<byte[]> asBytes =
client.send(request, HttpResponse.BodyHandlers.ofByteArray());
HttpResponse<Path> asFile =
client.send(request, HttpResponse.BodyHandlers.ofFile(Path.of("page.html")));
System.out.println(asText.body().length());
System.out.println(asBytes.body().length);
System.out.println(asFile.body());
}
}The calls are sequential. Each one finishes before the next begins, and each performs a separate HTTP exchange.
When send returns
What "finished" means depends on the handler.
- With
ofString,ofByteArrayandofFile,sendreturns only after the whole body has been read and processed. Readingresponse.body()afterwards does not touch the network. - With streaming handlers such as
ofInputStreamandofLines,sendreturns as soon as the status line and headers have arrived. The body is read later, as you consume the stream.
What the response gives you
The returned object carries more than the body. The following program prints the parts that matter right after a call.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Inspect {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com/")).build();
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("status : " + response.statusCode());
System.out.println("version : " + response.version());
System.out.println("uri : " + response.uri());
System.out.println("type : " + response.headers().firstValue("Content-Type").orElse("none"));
System.out.println("request : " + response.request().method());
}
}response.uri() is the final URI. If the client followed redirects, it differs from the URI you requested. response.version() reports whether the exchange used HTTP/1.1 or HTTP/2.
Failure modes
send has two separate ways to report trouble, and mixing them up is the most common mistake.
| Situation | Result of `send` |
|---|---|
| Server answers 404 or 500 | Returns normally. Check `statusCode()`. |
| Connect timeout | Throws `HttpConnectTimeoutException` |
| Request timeout | Throws `HttpTimeoutException` |
| DNS failure, refused connection, dropped connection | Throws `IOException` (for example `ConnectException`) |
| Calling thread interrupted while waiting | Throws `InterruptedException` |
| Malformed request such as a URI without a scheme | Throws `IllegalArgumentException` before any I/O |
HttpTimeoutException and HttpConnectTimeoutException both extend IOException. A handler for the subclass must appear before a handler for IOException, or the compiler rejects the code as unreachable.
A status of 404 is a successful HTTP exchange, so the call does not throw. If you skip the status check, you may parse an error page as if it were data.
A reusable wrapper
When many call sites need the same checks, put them in one method. This one turns non-2xx statuses into an exception of your own and restores the interrupt flag when needed.
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class Fetcher {
private final HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();
public static class HttpStatusException extends IOException {
private final int status;
public HttpStatusException(int status, String message) {
super(message);
this.status = status;
}
public int status() { return status; }
}
public String getText(String url) throws IOException {
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
.timeout(Duration.ofSeconds(10))
.build();
try {
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
int status = response.statusCode();
if (status < 200 || status >= 300) {
throw new HttpStatusException(status, "GET " + url + " returned " + status);
}
return response.body();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("Interrupted while calling " + url, e);
}
}
public static void main(String[] args) throws IOException {
System.out.println(new Fetcher().getText("https://example.com/").length());
}
}Catching InterruptedException and then continuing as if nothing happened hides a shutdown request from the rest of your program. Setting the flag again with Thread.currentThread().interrupt() preserves it for the code above you.
Edge cases and gotchas
- The timeout covers waiting for the response, not the whole transfer.
HttpRequest.timeoutlimits how long the client waits for the response to arrive. A slow body on a streaming handler is not bounded by it. Without a request timeout,sendcan block indefinitely. - Memory.
ofStringandofByteArrayhold the entire body in memory. For large payloads, useofFileorofInputStream. - Character set.
ofStringdecodes with the charset in the responseContent-Typeheader and falls back to UTF-8. Pass aCharsetexplicitly if the server's header is wrong. - Thread safety. One
HttpClientcan be shared by many threads, and each thread can callsendat the same time. Do not build a new client per call. A new client discards the connection reuse that makes later calls faster. - Blocking cost. Each blocked
sendholds one of your threads. For a few calls that is fine. For fan-out over many requests,sendAsyncfits better, and a later chapter covers it.
Exercise
A call to client.send(request, HttpResponse.BodyHandlers.ofString()) against your API returns, and response.body() holds an HTML error page. No exception was thrown and no timeout elapsed. What happened, and what code change prevents the page from being parsed as data?
Show answer
The server replied with a non-2xx status such as 404 or 500. send treats any completed HTTP exchange as a success, so it returned normally. Check response.statusCode() after the call and, when it is outside 200 to 299, throw your own exception or handle the error instead of reading the body as data.
Exercise
Why must catch (HttpTimeoutException e) appear before catch (IOException e), and what should you do inside catch (InterruptedException e)?
Show answer
HttpTimeoutException is a subclass of IOException. If the IOException handler comes first, it catches the timeout too, and the compiler reports the later handler as unreachable. In the InterruptedException handler, call Thread.currentThread().interrupt() to restore the interrupt flag, then stop or propagate the work.