eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

eBook – HTTP Client – NPI (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

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>5.0.0-alpha.12</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>5.0.0-alpha.12</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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – LS – NPI (cat=HTTP Client-Side)
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)