### Configure OkHttp3 Interceptor
Source: https://github.com/reportportal/logger-java-okhttp3/blob/develop/README.md
This Java code illustrates how to add the ReportPortalOkHttp3LoggingInterceptor to your OkHttp client's configuration. It's recommended to add this interceptor early in the chain, typically within a setup method like @BeforeClass or @BeforeAll.
```java
public class BaseTest {
private OkHttpClient client;
@BeforeClass
public void setupOkHttp3() {
client = new OkHttpClient.Builder().addInterceptor(new ReportPortalOkHttp3LoggingInterceptor(LogLevel.INFO))
.build();
}
}
```
--------------------------------
### Handle Multipart Requests with OkHttp3 Interceptor
Source: https://context7.com/reportportal/logger-java-okhttp3/llms.txt
Shows how the ReportPortalOkHttp3LoggingInterceptor automatically handles multipart requests. Text parts are logged inline, while binary parts like images or files are attached to Report Portal with their correct MIME types. This example demonstrates setting up the interceptor and performing a multipart upload.
```java
import com.epam.reportportal.listeners.LogLevel;
import com.epam.reportportal.okhttp3.ReportPortalOkHttp3LoggingInterceptor;
import okhttp3.*;
import java.io.File;
public class MultipartTest {
private OkHttpClient client;
@BeforeClass
public void setup() {
client = new OkHttpClient.Builder()
.addInterceptor(new ReportPortalOkHttp3LoggingInterceptor(LogLevel.INFO))
.build();
}
@Test
public void testMultipartUpload() throws IOException {
File imageFile = new File("test-image.jpg");
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("description", "Profile photo upload")
.addFormDataPart("userId", "12345")
.addFormDataPart("file", imageFile.getName(),
RequestBody.create(imageFile, MediaType.parse("image/jpeg")))
.build();
Request request = new Request.Builder()
.url("https://api.example.com/upload")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
// Log output will include:
// **>>> REQUEST** POST to https://api.example.com/upload
// Text parts logged inline in code blocks
// Image part logged with thumbnail attachment to Report Portal
}
}
```
--------------------------------
### Sanitize Request/Response Data with Converters
Source: https://github.com/reportportal/logger-java-okhttp3/blob/develop/README.md
This Java example shows how to configure the ReportPortalOkHttp3LoggingInterceptor with custom converters for sanitizing sensitive data like headers and authentication tokens. It demonstrates setting up Cookie, Header, and URI converters.
```java
public class BaseTest {
private OkHttpClient client;
@BeforeClass
public void setupOkHttp3() {
client = new OkHttpClient.Builder().addInterceptor(new ReportPortalOkHttp3LoggingInterceptor(LogLevel.INFO,
SanitizingHttpHeaderConverter.INSTANCE,
DefaultHttpHeaderConverter.INSTANCE
))
.authenticator((route, response) -> {
String credential = "Bearer test_token";
return response.request().newBuilder().header("Authorization", credential).build();
})
.followRedirects(true)
.build();
}
}
```
--------------------------------
### Configure ReportPortalOkHttp3LoggingInterceptor
Source: https://context7.com/reportportal/logger-java-okhttp3/llms.txt
Demonstrates how to integrate the ReportPortalOkHttp3LoggingInterceptor into an OkHttpClient instance. The interceptor automatically logs all HTTP traffic at the specified log level.
```java
import com.epam.reportportal.listeners.LogLevel;
import com.epam.reportportal.okhttp3.ReportPortalOkHttp3LoggingInterceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.MediaType;
import okhttp3.RequestBody;
public class ApiTest {
private OkHttpClient client;
@BeforeClass
public void setupOkHttp3() {
client = new OkHttpClient.Builder()
.addInterceptor(new ReportPortalOkHttp3LoggingInterceptor(LogLevel.INFO))
.build();
}
@Test
public void testApiCall() throws IOException {
Request request = new Request.Builder()
.url("https://api.example.com/users")
.post(RequestBody.create(
"{\"name\": \"John\", \"email\": \"john@example.com\"}",
MediaType.parse("application/json")
))
.addHeader("Authorization", "Bearer token123")
.build();
Response response = client.newCall(request).execute();
}
}
```
--------------------------------
### Initialize Interceptor with Custom Converters
Source: https://context7.com/reportportal/logger-java-okhttp3/llms.txt
Shows how to configure the interceptor with custom converters for headers, cookies, and parameters. This is essential for sanitizing sensitive data like authorization tokens before they are logged.
```java
import com.epam.reportportal.formatting.http.converters.*;
import com.epam.reportportal.listeners.LogLevel;
import com.epam.reportportal.okhttp3.ReportPortalOkHttp3LoggingInterceptor;
import okhttp3.OkHttpClient;
public class SecureApiTest {
private OkHttpClient client;
@BeforeClass
public void setupSecureLogging() {
ReportPortalOkHttp3LoggingInterceptor interceptor = new ReportPortalOkHttp3LoggingInterceptor(
LogLevel.INFO,
SanitizingHttpHeaderConverter.INSTANCE,
DefaultHttpHeaderConverter.INSTANCE,
DefaultCookieConverter.INSTANCE,
DefaultUriConverter.INSTANCE,
DefaultFormParamConverter.INSTANCE
);
client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.build();
}
}
```
--------------------------------
### Custom Http Request/Response Formatting with HttpEntityFactory
Source: https://context7.com/reportportal/logger-java-okhttp3/llms.txt
Demonstrates how to use HttpEntityFactory to create custom formatters for OkHttp3 requests and responses. This allows for detailed logging of HTTP traffic within test reports, including headers and bodies. It utilizes various converters for different parts of the HTTP message.
```java
import com.epam.reportportal.formatting.http.HttpRequestFormatter;
import com.epam.reportportal.formatting.http.HttpResponseFormatter;
import com.epam.reportportal.formatting.http.converters.*;
import com.epam.reportportal.formatting.http.entities.BodyType;
import com.epam.reportportal.okhttp3.support.HttpEntityFactory;
import okhttp3.*;
import java.util.Collections;
import java.util.Map;
public class CustomFormatterExample {
public void processRequest(Request request) {
// Create formatter from OkHttp3 Request
HttpRequestFormatter requestFormatter = HttpEntityFactory.createHttpRequestFormatter(
request,
DefaultUriConverter.INSTANCE, // URI converter
DefaultHttpHeaderConverter.INSTANCE, // Header converter
DefaultCookieConverter.INSTANCE, // Cookie converter
DefaultFormParamConverter.INSTANCE, // Form param converter
Collections.emptyMap(), // Content prettifiers
DefaultHttpHeaderConverter.INSTANCE, // Multipart header converter
Collections.emptyMap() // Body type map
);
// Get formatted request as Markdown string
String formattedRequest = requestFormatter.toString();
// Output: **>>> REQUEST** POST to http://example.com
// **Headers**
// Content-Type: application/json
// **Body**
// ```
// {"key": "value"}
// ```
}
public void processResponse(Response response) {
// Create formatter from OkHttp3 Response
HttpResponseFormatter responseFormatter = HttpEntityFactory.createHttpResponseFormatter(
response,
DefaultHttpHeaderConverter.INSTANCE, // Header converter
DefaultCookieConverter.INSTANCE, // Cookie converter
Collections.emptyMap(), // Content prettifiers
Collections.emptyMap() // Body type map
);
String formattedResponse = responseFormatter.toString();
// Output: **<<< RESPONSE** 200
// **Headers**
// Content-Type: application/json
// **Body**
// ```
// {"result": "success"}
// ```
}
}
```
--------------------------------
### Add OkHttp3 Logger Dependency (Gradle)
Source: https://github.com/reportportal/logger-java-okhttp3/blob/develop/README.md
This snippet demonstrates how to include the ReportPortalOkHttp3LoggingInterceptor in your Gradle project. Add this line to your build.gradle file to manage the dependency.
```groovy
dependencies {
testCompile 'com.epam.reportportal:logger-java-okhttp3:5.3.0'
}
```
--------------------------------
### Add OkHttp3 Logger Dependency (Maven)
Source: https://github.com/reportportal/logger-java-okhttp3/blob/develop/README.md
This snippet shows how to add the ReportPortalOkHttp3LoggingInterceptor as a dependency in your Maven project's pom.xml file. Ensure you use the latest version available on Maven Central.
```xml
com.epam.reportportal
logger-java-okhttp3
5.3.0
```
--------------------------------
### Add logger-java-okhttp3 dependency to Gradle project
Source: https://github.com/reportportal/logger-java-okhttp3/blob/develop/README_TEMPLATE.md
Add the logger-java-okhttp3 library to your Gradle project's build.gradle file to integrate Report Portal logging with OkHttp3.
```groovy
dependencies {
testCompile 'com.epam.reportportal:logger-java-okhttp3:$LATEST_VERSION'
}
```
--------------------------------
### Configure Content Prettifiers for MIME Types
Source: https://context7.com/reportportal/logger-java-okhttp3/llms.txt
Configures custom prettifiers to format raw HTTP body content into human-readable structures like JSON, XML, or HTML. It maps specific MIME types to their corresponding prettifier instances.
```java
Map> customPrettifiers = new HashMap<>() {{
put(ContentType.APPLICATION_XML.getMimeType(), XmlPrettifier.INSTANCE);
put(ContentType.APPLICATION_JSON.getMimeType(), JsonPrettifier.INSTANCE);
put(ContentType.TEXT_HTML.getMimeType(), HtmlPrettier.INSTANCE);
}};
ReportPortalOkHttp3LoggingInterceptor interceptor = new ReportPortalOkHttp3LoggingInterceptor(LogLevel.INFO)
.setContentPrettiers(customPrettifiers);
```
--------------------------------
### Apply Custom Content Prettiers
Source: https://github.com/reportportal/logger-java-okhttp3/blob/develop/README.md
This Java code demonstrates how to apply custom content prettiers to the ReportPortalOkHttp3LoggingInterceptor for specific content types like XML and JSON. It defines a map of MIME types to their respective prettier instances.
```java
public class BaseTest {
private static final Map> MY_PRETTIERS = new HashMap>() {{
put(ContentType.APPLICATION_XML.getMimeType(), XmlPrettier.INSTANCE);
put(ContentType.APPLICATION_SOAP_XML.getMimeType(), XmlPrettier.INSTANCE);
put(ContentType.APPLICATION_ATOM_XML.getMimeType(), XmlPrettier.INSTANCE);
put(ContentType.APPLICATION_SVG_XML.getMimeType(), XmlPrettier.INSTANCE);
put(ContentType.APPLICATION_XHTML_XML.getMimeType(), XmlPrettier.INSTANCE);
put(ContentType.TEXT_XML.getMimeType(), XmlPrettier.INSTANCE);
put(ContentType.APPLICATION_JSON.getMimeType(), JsonPrettier.INSTANCE);
put("text/json", JsonPrettier.INSTANCE);
put(ContentType.TEXT_HTML.getMimeType(), HtmlPrettier.INSTANCE);
}};
private OkHttpClient client;
@BeforeClass
public void setupOkHttp3() {
client = new OkHttpClient.Builder().addInterceptor(new ReportPortalOkHttp3LoggingInterceptor(LogLevel.INFO).setContentPrettiers(
MY_PRETTIERS)).build();
}
}
```
--------------------------------
### Add Request Filters to OkHttp3 Interceptor
Source: https://context7.com/reportportal/logger-java-okhttp3/llms.txt
Demonstrates how to add request filters to the ReportPortalOkHttp3LoggingInterceptor to conditionally skip logging for certain HTTP requests. Filters are implemented as predicates that return true to prevent logging. This is useful for excluding health checks, static assets, or requests to specific domains.
```java
import com.epam.reportportal.listeners.LogLevel;
import com.epam.reportportal.okhttp3.ReportPortalOkHttp3LoggingInterceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import java.util.function.Predicate;
public class FilteredLoggingTest {
private OkHttpClient client;
@BeforeClass
public void setupWithFilters() {
ReportPortalOkHttp3LoggingInterceptor interceptor =
new ReportPortalOkHttp3LoggingInterceptor(LogLevel.INFO)
// Skip health check endpoints
.addRequestFilter(request -> request.url().encodedPath().contains("/health"))
// Skip static assets
.addRequestFilter(request -> {
String path = request.url().encodedPath();
return path.endsWith(".css") || path.endsWith(".js") || path.endsWith(".png");
})
// Skip requests to external services
.addRequestFilter(request ->
!request.url().host().contains("api.mycompany.com")
);
client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.build();
// Requests matching any filter will NOT be logged to Report Portal
}
}
```
--------------------------------
### ReportPortalOkHttp3LoggingInterceptor
Source: https://context7.com/reportportal/logger-java-okhttp3/llms.txt
The primary interceptor class used to capture and log HTTP traffic to Report Portal. It integrates directly into the OkHttp3 client pipeline.
```APIDOC
## ReportPortalOkHttp3LoggingInterceptor
### Description
An OkHttp3 Interceptor that automatically intercepts requests and responses, formatting them into Markdown for Report Portal logs.
### Method
N/A (Interceptor Implementation)
### Parameters
#### Constructor Parameters
- **logLevel** (LogLevel) - Required - The Report Portal logging level (e.g., INFO, DEBUG).
### Request Example
```java
client = new OkHttpClient.Builder()
.addInterceptor(new ReportPortalOkHttp3LoggingInterceptor(LogLevel.INFO))
.build();
```
### Response
- **Logging Behavior** - Automatically logs request/response details including headers, cookies, and body content to the active Report Portal execution.
```
--------------------------------
### Add logger-java-okhttp3 dependency to Maven project
Source: https://github.com/reportportal/logger-java-okhttp3/blob/develop/README_TEMPLATE.md
Include the logger-java-okhttp3 library in your Maven project's pom.xml to enable Report Portal logging for OkHttp3 requests and responses.
```xml
com.epam.reportportal
logger-java-okhttp3
$LATEST_VERSION
```
--------------------------------
### Custom Converters and Sanitization
Source: https://context7.com/reportportal/logger-java-okhttp3/llms.txt
Configuration for the interceptor using custom converters to sanitize sensitive data such as Authorization headers or cookies before logging.
```APIDOC
## Custom Converters Configuration
### Description
Allows fine-grained control over how HTTP entities are logged, enabling the use of sanitizers to mask sensitive information.
### Parameters
#### Constructor Parameters
- **logLevel** (LogLevel) - Required - The logging level.
- **headerConverter** (HttpHeaderConverter) - Optional - Converter for request/response headers.
- **cookieConverter** (CookieConverter) - Optional - Converter for cookies.
- **uriConverter** (UriConverter) - Optional - Converter for URI formatting.
- **formParamConverter** (FormParamConverter) - Optional - Converter for form parameters.
### Request Example
```java
ReportPortalOkHttp3LoggingInterceptor interceptor = new ReportPortalOkHttp3LoggingInterceptor(
LogLevel.INFO,
SanitizingHttpHeaderConverter.INSTANCE,
DefaultHttpHeaderConverter.INSTANCE,
DefaultCookieConverter.INSTANCE,
DefaultUriConverter.INSTANCE,
DefaultFormParamConverter.INSTANCE
);
```
```
--------------------------------
### Mask Sensitive Headers with Custom Converter
Source: https://context7.com/reportportal/logger-java-okhttp3/llms.txt
Implements a custom header converter using the Function interface to mask sensitive information like authorization tokens. This ensures sensitive data is not exposed in the ReportPortal logs.
```java
Function customHeaderConverter = header -> {
if (SENSITIVE_HEADERS.contains(header.getName().toLowerCase())) {
return header.getName() + ": ***MASKED***";
}
return header.getName() + ": " + header.getValue();
};
ReportPortalOkHttp3LoggingInterceptor interceptor = new ReportPortalOkHttp3LoggingInterceptor(
LogLevel.INFO,
customHeaderConverter,
customHeaderConverter
);
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.