Skip to content
This repository has been archived by the owner on Oct 30, 2022. It is now read-only.

meeshkan/java-http-types

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

51 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

http-types in Java

Build Status MIT licensed Package on Maven Central javadoc

Java (8 or later) library to read and write records of HTTP exchanges in the http-types format.

Using this library

Releases are available on Maven Central.

dependencies {
    implementation 'com.meeshkan:http-types:0.5.0'
}

Writing HTTP exchanges

Using HttpExchangeWriter a recording of HTTP traffic can be serialised for use with any program that can handle the HTTP Types format.

try (var writer = new HttpExchangeWriter(new FileOutputStream("output.jsonl"))) {
    HttpRequest request = new HttpRequest.Builder()
        .method(HttpMethod.GET)
        .url(new HttpUrl.Builder()
            .protocol(HttpProtocol.HTTP)
            .host("example.com")
            .pathname("/path")
            .queryParameters(Collections.singletonMap("param", "value"))
            .build())    
        .headers(new HttpHeaders.Builder()
            .add("header1", "value1")
            .add("header2", "value2")
            .build())
        .body("requestBody")
        .build();

    HttpResponse = new HttpResponse.Builder()
        .statusCode(200)
        .headers(new HttpHeaders.Builder()
            .add("header", "value")
            .build())
        .body("responseBody")
        .build());

    HttpExchange exchange = new HttpExchange.Builder()
            .request(request)
            .response(response)
            .build();

    writer.write(exchange);
    
    // Normally you would write multiple exchanges in the same recording.
}

Reading HTTP exchanges

With HttpExchangeReader HTTP Types recordings can be read for processing:

InputStream input = getClass().getResourceAsStream("/sample.jsonl");

HttpExchangeReader
    .fromJsonLines(input)
    .filter(exchange -> exchange.getResponse().getStatusCode() == 200)
    .forEach(exchange -> {
        HttpRequest request = exchange.getRequest();
        HttpUrl url = request.getUrl();
        HttpResponse response = exchange.getResponse();

        System.out.println("A " + request.getMethod() + " request to " +
            url.getHost() + " with response body " + response.getBody());
});