PUBLIC OBJECT

Basic HTTP/1.1 with Okio

In a post on The Corner on Wednesday I claimed that OkHttp is one of the most challenging projects I've worked on. Here's the proof that I was lying: an HTTP request in 12 lines of code.

    Socket socket = new Socket("square.com", 80);

    BufferedSink sink = Okio.buffer(Okio.sink(socket));
    sink.timeout().timeout(5, TimeUnit.SECONDS);
    sink.writeUtf8("GET / HTTP/1.1\r\n");
    sink.writeUtf8("Host: square.com\r\n");
    sink.writeUtf8("\r\n");
    sink.flush();

    BufferedSource source = Okio.buffer(Okio.source(socket));
    source.timeout().timeout(5, TimeUnit.SECONDS);
    for (String line; (line = source.readUtf8LineStrict()) != null; ) {
      System.out.println(line);
    }

One neat method in this code sample is readUtf8LineStrict(). This is like BufferedReader.readLine(), except it throws an EOFException if the input is exhausted before the \n is encountered. That way the parser won't silently ignore truncated input.

There's another method, BufferedSource.readUtf8Line(), that behaves exactly like BufferedReader.readLine(). That's the one you want to use for human-edited text. Unlike computers, humans can't be trusted to include trailing newlines, and they shouldn't be punished for omitting them.

Get Okio on GitHub.