diff --git a/libraries-http-2/pom.xml b/libraries-http-2/pom.xml index d0bdb26bd4..855008521f 100644 --- a/libraries-http-2/pom.xml +++ b/libraries-http-2/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 libraries-http-2 libraries-http-2 @@ -13,12 +13,17 @@ - + com.squareup.okhttp3 okhttp ${okhttp.version} + + com.squareup.okhttp3 + logging-interceptor + ${okhttp.version} + com.fasterxml.jackson.core jackson-databind @@ -81,9 +86,9 @@ - 3.14.2 + 4.9.1 2.8.5 - 3.14.2 + 4.9.1 1.0.3 9.4.19.v20190610 2.2.11 diff --git a/libraries-http-2/src/main/java/com/baeldung/okhttp/interceptors/CacheControlResponeInterceptor.java b/libraries-http-2/src/main/java/com/baeldung/okhttp/interceptors/CacheControlResponeInterceptor.java new file mode 100644 index 0000000000..e9f8db19be --- /dev/null +++ b/libraries-http-2/src/main/java/com/baeldung/okhttp/interceptors/CacheControlResponeInterceptor.java @@ -0,0 +1,18 @@ +package com.baeldung.okhttp.interceptors; + +import java.io.IOException; + +import okhttp3.Interceptor; +import okhttp3.Response; + +public class CacheControlResponeInterceptor implements Interceptor { + + @Override + public Response intercept(Chain chain) throws IOException { + Response response = chain.proceed(chain.request()); + return response.newBuilder() + .header("Cache-Control", "no-store") + .build(); + } + +} diff --git a/libraries-http-2/src/main/java/com/baeldung/okhttp/interceptors/ErrorMessage.java b/libraries-http-2/src/main/java/com/baeldung/okhttp/interceptors/ErrorMessage.java new file mode 100644 index 0000000000..73411d947f --- /dev/null +++ b/libraries-http-2/src/main/java/com/baeldung/okhttp/interceptors/ErrorMessage.java @@ -0,0 +1,21 @@ +package com.baeldung.okhttp.interceptors; + +public class ErrorMessage { + + private final int status; + private final String detail; + + public ErrorMessage(int status, String detail) { + this.status = status; + this.detail = detail; + } + + public int getStatus() { + return status; + } + + public String getDetail() { + return detail; + } + +} diff --git a/libraries-http-2/src/main/java/com/baeldung/okhttp/interceptors/ErrorResponseInterceptor.java b/libraries-http-2/src/main/java/com/baeldung/okhttp/interceptors/ErrorResponseInterceptor.java new file mode 100644 index 0000000000..f6c6673705 --- /dev/null +++ b/libraries-http-2/src/main/java/com/baeldung/okhttp/interceptors/ErrorResponseInterceptor.java @@ -0,0 +1,32 @@ +package com.baeldung.okhttp.interceptors; + +import java.io.IOException; + +import com.google.gson.Gson; + +import okhttp3.Interceptor; +import okhttp3.MediaType; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class ErrorResponseInterceptor implements Interceptor { + + public static final MediaType APPLICATION_JSON = MediaType.get("application/json; charset=utf-8"); + + @Override + public Response intercept(Chain chain) throws IOException { + Response response = chain.proceed(chain.request()); + + if(!response.isSuccessful()) { + Gson gson = new Gson(); + String body = gson.toJson(new ErrorMessage(response.code(), "The response from the server was not OK")); + ResponseBody responseBody = ResponseBody.create(body, APPLICATION_JSON); + + return response.newBuilder() + .body(responseBody) + .build(); + } + return response; + } + +} diff --git a/libraries-http-2/src/main/java/com/baeldung/okhttp/interceptors/SimpleLoggingInterceptor.java b/libraries-http-2/src/main/java/com/baeldung/okhttp/interceptors/SimpleLoggingInterceptor.java new file mode 100644 index 0000000000..6d08546eea --- /dev/null +++ b/libraries-http-2/src/main/java/com/baeldung/okhttp/interceptors/SimpleLoggingInterceptor.java @@ -0,0 +1,25 @@ +package com.baeldung.okhttp.interceptors; + +import java.io.IOException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import okhttp3.Interceptor; +import okhttp3.Request; +import okhttp3.Response; + +public class SimpleLoggingInterceptor implements Interceptor { + + private static final Logger LOGGER = LoggerFactory.getLogger(SimpleLoggingInterceptor.class); + + @Override + public Response intercept(Chain chain) throws IOException { + Request request = chain.request(); + + LOGGER.info("Intercepted headers: {} from URL: {}", request.headers(), request.url()); + + return chain.proceed(request); + } + +} diff --git a/libraries-http-2/src/test/java/com/baeldung/okhttp/interceptors/InterceptorIntegrationTest.java b/libraries-http-2/src/test/java/com/baeldung/okhttp/interceptors/InterceptorIntegrationTest.java new file mode 100644 index 0000000000..d15b67ad3b --- /dev/null +++ b/libraries-http-2/src/test/java/com/baeldung/okhttp/interceptors/InterceptorIntegrationTest.java @@ -0,0 +1,90 @@ +package com.baeldung.okhttp.interceptors; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; + +import org.junit.Rule; +import org.junit.Test; + +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.logging.HttpLoggingInterceptor; +import okhttp3.logging.HttpLoggingInterceptor.Level; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; + +public class InterceptorIntegrationTest { + + @Rule + public MockWebServer server = new MockWebServer(); + + @Test + public void givenSimpleLogginInterceptor_whenRequestSent_thenHeadersLogged() throws IOException { + server.enqueue(new MockResponse().setBody("Hello Baeldung Readers!")); + + OkHttpClient client = new OkHttpClient.Builder() + .addNetworkInterceptor(new SimpleLoggingInterceptor()) + .build(); + + Request request = new Request.Builder() + .url(server.url("/greeting")) + .header("User-Agent", "A Baeldung Reader") + .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()); + } + } + + @Test + public void givenResponseInterceptor_whenRequestSent_thenCacheControlSetToNoStore() throws IOException { + server.enqueue(new MockResponse().setBody("Hello Baeldung Readers!")); + + OkHttpClient client = new OkHttpClient.Builder() + .addInterceptor(getHttpLogger()) + .addInterceptor(new CacheControlResponeInterceptor()) + .build(); + + Request request = new Request.Builder() + .url(server.url("/greeting")) + .header("User-Agent", "A Baeldung Reader") + .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()); + assertEquals("Response cache-control should be", "no-store", response.header("Cache-Control")); + } + } + + @Test + public void givenErrorResponseInterceptor_whenResponseIs500_thenBodyIsJsonWithStatus() throws IOException { + server.enqueue(new MockResponse().setResponseCode(500).setBody("Hello Baeldung Readers!")); + + OkHttpClient client = new OkHttpClient.Builder() + .addInterceptor(getHttpLogger()) + .addInterceptor(new ErrorResponseInterceptor()) + .build(); + + Request request = new Request.Builder() + .url(server.url("/greeting")) + .header("User-Agent", "A Baeldung Reader") + .build(); + + try (Response response = client.newCall(request).execute()) { + assertEquals("Response code should be: ", 500, response.code()); + assertEquals("Body should be: ", "{\"status\":500,\"detail\":\"The response from the server was not OK\"}", + response.body().string()); + } + } + + private HttpLoggingInterceptor getHttpLogger() { + HttpLoggingInterceptor logger = new HttpLoggingInterceptor(); + logger.setLevel(Level.HEADERS); + return logger; + } + +}