BAEL-4204 - Adding Interceptors in OkHTTP (#10539)
* BAEL-4706 - Spring Boot with Spring Batch * BAEL-3948 - Fix test(s) in spring-batch which leaves repository.sqlite changed * BAEL-4736 - Convert JSONArray to List of Object using camel-jackson * BAEL-4756 - Mockito MockSettings * BAEL-4756 - Mockito MockSettings - fix spelling * BAEL-2674 - Upgrade the Okhttp article * BAEL-4204 - Adding Interceptors in OkHTTP Co-authored-by: Jonathan Cook <jcook@sciops.esa.int>
This commit is contained in:
parent
ab0cef67fb
commit
49da1ed251
@ -1,7 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
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">
|
||||
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">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>libraries-http-2</artifactId>
|
||||
<name>libraries-http-2</name>
|
||||
@ -13,12 +13,17 @@
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- Dependencies for response decoder with okhttp -->
|
||||
<!-- Dependencies for response decoder with okhttp -->
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>okhttp</artifactId>
|
||||
<version>${okhttp.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>logging-interceptor</artifactId>
|
||||
<version>${okhttp.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
@ -81,9 +86,9 @@
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<okhttp.version>3.14.2</okhttp.version>
|
||||
<okhttp.version>4.9.1</okhttp.version>
|
||||
<gson.version>2.8.5</gson.version>
|
||||
<mockwebserver.version>3.14.2</mockwebserver.version>
|
||||
<mockwebserver.version>4.9.1</mockwebserver.version>
|
||||
<jetty.httpclient.version>1.0.3</jetty.httpclient.version>
|
||||
<jetty.server.version>9.4.19.v20190610</jetty.server.version>
|
||||
<rxjava2.version>2.2.11</rxjava2.version>
|
||||
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user