An awkward API
OkHttp 1.0 started out as an optimized implementation of
HttpURLConnection. This old API is awkward to implement because there is an implicit state machine that corresponds to the underlying network I/O.
GET / HTTP/1.1 Host: publicobject.com Accept: text/html HTTP/1.1 200 OK Content-Length: 300 <html> <head><title>Public Object</title></head> ...
For example, calling
getResponseCode() forbids future calls to
setRequestProperty() because request headers can’t be edited after they’ve been transmitted.
HttpURLConnection connection = urlFactory.open(url); int responseCode = connection.getResponseCode(); // This fails with an exception at runtime! connection.setRequestProperty("Accept", "text/html");
What’s safe to call is especially awkward because the state machine itself is dynamic:
setChunkedStreamingMode() cause request body writes to lock in request headers.
An uncomfortable implementation
With OkHttp 2.0 we introduced a new API to complement
HttpURLConnection. Instead of an implicit state machine the new API uses types to make an explicit model:
Request has the inputs,
Response has the outputs, and
Call does the action.
Request request = new Request.Builder() .url(url) .header("Accept", "text/html") .build(); Call call = client.newCall(request