Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4535

A Guide to Events in OkHTTP

$
0
0

1. Overview

Typically when working with HTTP calls in our web applications, we'll want a way to capture some kind of metrics about the requests and responses. Usually, this is to monitor the size and frequency of the HTTP calls our application makes.

OkHttp is an efficient HTTP & HTTP/2 client for Android and Java applications. In a previous tutorial, we looked at the basics of how to work with OkHttp.

In this tutorial, we'll learn all about how we can capture these types of metrics using events.

2. Events

As the name suggests, events provide a powerful mechanism for us to record application metrics relating to the entire HTTP call life cycle.

In order to subscribe to the events we are interested in all, we need to do is define an EventListener and override the methods for the events we want to capture.

This is particularly useful if, for example, we only want to monitor failed and successful calls. In that case, we simply override the specific methods that correspond to those events within our event listener class. We'll see this in more detail later.

There is at least a couple of advantages to using events in our applications:

  • We can use events to monitor the size and frequency of the HTTP calls our application makes
  • This can help us quickly determine where we might have a bottleneck in our application

Finally, we can also use events to determine if we have an underlying problem with our network as well.

3. Dependencies

Of course, we'll need to add the standard okhttp dependency to our pom.xml:

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.9.1</version>
</dependency>

We'll also need another dependency specifically for our tests. Let's add the OkHttp mockwebserver artifact:

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>mockwebserver</artifactId>
    <version>4.9.1</version>
    <scope>test</scope>
</dependency>

Now that we have all the necessary dependencies configured, we can go ahead and write our first event listener.

4. Event Methods and Order

But before we start defining our own event listener, we're going to take a step back and briefly look at what event methods are available to us and also the order we can expect events to arrive in. This will help us when we dive into some real examples later on.

Let's assume we're dealing with a successful HTTP call with no redirects or retries. Then we can expect this typical flow of method calls.

4.1. callStart()

This method is our entry point, and we'll invoke it as soon as we enqueue a call or our client executes it.

4.2. proxySelectStart() and proxySelectEnd()

The first method is invoked prior to a proxy selection and likewise after proxy selection, including the lists of proxies in the order they will be attempted. This list can, of course, be empty if no proxy is configured.

4.3. dnsStart() and dnsEnd()

These methods are invoked just before DNS lookup and immediately after the DNS is resolved.

4.4. connectStart() and connectEnd()

These methods are invoked prior to establishing and closing a socket connection.

4.5. secureConnectStart() and secureConnectEnd()

If our call uses HTTPS, then interspersed between connectStart and connectEnd we'll have these secure connect variations.

4.6. connectionAcquired() and connectionReleased()

Called after a connection has been acquired or released.

4.7. requestHeadersStart() and requestHeadersEnd()

These methods will be invoked immediately prior to and after sending request headers.

4.8. requestBodyStart() and requestBodyEnd()

As the name suggests, invoked prior to sending a request body. Of course, this will only apply to requests that contain a body.

4.9. responseHeadersStart() and responseHeadersEnd()

These methods are called when response headers are first returned from the server and immediately after they are received.

4.10. responseBodyStart() and responseBodyEnd()

Likewise, called when the response body is first returned from the server and immediately after the body is received.

In addition to these methods, we also have three additional methods we can use for capturing failures:

4.11. callFailed(), responseFailed(), and requestFailed()

If our call fails permanently, the request has a write failure, or the response has a read failure.

5. Defining a Simple Event Listener

Let's start by defining our own even listener. To keep things really simple, our event listener will log when the call starts and ends along with some request and response header information:

public class SimpleLogEventsListener extends EventListener {
    private static final Logger LOGGER = LoggerFactory.getLogger(SimpleLogEventsListener.class);
    @Override
    public void callStart(Call call) {
        LOGGER.info("callStart at {}", LocalDateTime.now());
    }
    @Override
    public void requestHeadersEnd(Call call, Request request) {
        LOGGER.info("requestHeadersEnd at {} with headers {}", LocalDateTime.now(), request.headers());
    }
    @Override
    public void responseHeadersEnd(Call call, Response response) {
        LOGGER.info("responseHeadersEnd at {} with headers {}", LocalDateTime.now(), response.headers());
    }
    @Override
    public void callEnd(Call call) {
        LOGGER.info("callEnd at {}", LocalDateTime.now());
    }
}

As we can see, to create our listener, all we need to do is extend from the EventListener class. Then we can go ahead and override the methods for the events we care about.

In our simple listener, we log the time the call starts and ends along with the request and response headers when they arrive.

5.1. Plugging It Together

To actually make use of this listener, all we need to do is call the eventListener method when we build our OkHttpClient instance, and it should just work:

OkHttpClient client = new OkHttpClient.Builder() 
  .eventListener(new SimpleLogEventsListener())
  .build();

In the next section, we'll take a look at how we can test our new listener.

5.2. Testing the Event Listener

Now, we have defined our first event listener; let's go ahead and write our first integration test:

@Rule
public MockWebServer server = new MockWebServer();
@Test
public void givenSimpleEventLogger_whenRequestSent_thenCallsLogged() throws IOException {
    server.enqueue(new MockResponse().setBody("Hello Baeldung Readers!"));
        
    OkHttpClient client = new OkHttpClient.Builder()
      .eventListener(new SimpleLogEventsListener())
      .build();
    Request request = new Request.Builder()
      .url(server.url("/"))
      .build();
    try (Response response = client.newCall(request).execute()) {
        assertEquals("Response code should be: ", 200, response.code());
        assertEquals("Body should be: ", "Hello Baeldung Readers!", response.body().string());
    }
 }

First of all, we are using the OkHttp MockWebServer JUnit rule.

This is a lightweight, scriptable web server for testing HTTP clients that we're going to use to test our event listeners. By using this rule, we'll create a clean instance of the server for every integration test.

With that in mind, let's now walk through the key parts of our test:

  • First of all, we set up a mock response that contains a simple message in the body
  • Then, we build our OkHttpClient and configure our SimpleLogEventsListener
  • Finally, we send the request and check the response code and body received using assertions

5.3. Running the Test

When we run our test, we'll see our events logged:

callStart at 2021-05-04T17:51:33.024
...
requestHeadersEnd at 2021-05-04T17:51:33.046 with headers User-Agent: A Baeldung Reader
Host: localhost:51748
Connection: Keep-Alive
Accept-Encoding: gzip
...
responseHeadersEnd at 2021-05-04T17:51:33.053 with headers Content-Length: 23
callEnd at 2021-05-04T17:51:33.055

6. Putting It All Together

Now let's imagine we want to build on our simple logging example and record the elapsed times for each of the steps in our call chain:

public class EventTimer extends EventListener {
    private long start;
    private void logTimedEvent(String name) {
        long now = System.nanoTime();
        if (name.equals("callStart")) {
            start = now;
        }
        long elapsedNanos = now - start;
        System.out.printf("%.3f %s%n", elapsedNanos / 1000000000d, name);
    }
    @Override
    public void callStart(Call call) {
        logTimedEvent("callStart");
    }
    // More event listener methods
}

This is very similar to our first example, but this time we capture the elapsed time from when our call started for each event. Typically this could be quite interesting to detect network latency.

Let's take a look if we run this against a real site like our very own https://www.baeldung.com/:

0.000 callStart
0.012 proxySelectStart
0.012 proxySelectEnd
0.012 dnsStart
0.175 dnsEnd
0.183 connectStart
0.248 secureConnectStart
0.608 secureConnectEnd
0.608 connectEnd
0.609 connectionAcquired
0.612 requestHeadersStart
0.613 requestHeadersEnd
0.706 responseHeadersStart
0.707 responseHeadersEnd
0.765 responseBodyStart
0.765 responseBodyEnd
0.765 connectionReleased
0.765 callEnd

As this call is going over HTTPS, we'll also see the secureConnectStart and secureConnectStart events.

7. Monitoring Failed Calls

Up until now, we've focussed on successfully HTTP requests, but we can also capture failed events:

@Test (expected = SocketTimeoutException.class)
public void givenConnectionError_whenRequestSent_thenFailedCallsLogged() throws IOException {
    OkHttpClient client = new OkHttpClient.Builder()
      .eventListener(new EventTimer())
      .build();
    Request request = new Request.Builder()
      .url(server.url("/"))
      .build();
    client.newCall(request).execute();
}

In this example, we've deliberately avoided setting up our mock web server, which means, of course, we'll see a catastrophic failure in the form of a SocketTimeoutException.

Let's take a look at the output when we run our test now:

0.000 callStart
...
10.008 responseFailed
10.009 connectionReleased
10.009 callFailed

As expected, we'll see our call start, and then after 10 seconds, the connection timeout occurs, and consequently, we see the responseFailed and callFailed events logged.

8. A Quick Word on Concurrency

So far, we have assumed that we do not have multiple calls executing concurrently. If we want to accommodate this scenario, then we need to use the eventListenerFactory method when we configure our OkHttpClient.

We can use a factory to create a new EventListener instance for each HTTP call. When we use this approach, it is possible to keep a call-specific state in our listener.

9. Conclusion

In this article, we've learned all about how to capture events using OkHttp. First, we began by explaining what an event is and understanding what kind of events are available to us and the order they arrive in when processing an HTTP call.

Then we took a look at how we can define a simple event logger to capture parts of our HTTP calls and how to write an integration test.

As always, the full source code of the article is available over on GitHub.

The post A Guide to Events in OkHTTP first appeared on Baeldung.
       

Viewing all articles
Browse latest Browse all 4535

Trending Articles