From 161f8212ab6e7f5b567eece1de1f2a7883b8ef79 Mon Sep 17 00:00:00 2001 From: codami Date: Mon, 11 Oct 2021 20:52:33 +0200 Subject: [PATCH] Fix for #22 - Handling of gzip encoding --- .../java/io/adven/grpc/wiremock/HttpMock.java | 25 +++++++++++++++---- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/src/main/java/io/adven/grpc/wiremock/HttpMock.java b/src/main/java/io/adven/grpc/wiremock/HttpMock.java index 7fdbde9..dfb50b7 100644 --- a/src/main/java/io/adven/grpc/wiremock/HttpMock.java +++ b/src/main/java/io/adven/grpc/wiremock/HttpMock.java @@ -13,7 +13,9 @@ import org.springframework.stereotype.Component; import javax.annotation.PreDestroy; +import java.io.InputStream; import java.io.IOException; +import java.io.UncheckedIOException; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.net.http.HttpClient; @@ -22,6 +24,7 @@ import java.util.HashMap; import java.util.Map; import java.util.stream.Stream; +import java.util.zip.GZIPInputStream; import static io.adven.grpc.wiremock.HeaderPropagationInterceptor.HEADERS; @@ -86,7 +89,7 @@ public Response request(String path, Object message, Map headers .POST(asJson(message)) .headers(headers.entrySet().stream().flatMap(e -> Stream.of(e.getKey(), e.getValue())).toArray(String[]::new)) .build(), - HttpResponse.BodyHandlers.ofString() + HttpResponse.BodyHandlers.ofInputStream() ) ); } @@ -96,22 +99,34 @@ public Response request(String path, Object message) throws IOException, Interru } public static final class Response { - private final HttpResponse httpResponse; + private final HttpResponse httpResponse; - public Response(HttpResponse httpResponse) { + public Response(HttpResponse httpResponse) { this.httpResponse = httpResponse; } public Message getMessage(Class aClass) { if (httpResponse.statusCode() == 200) { - return ProtoJsonUtil.fromJson(httpResponse.body(), aClass); + return ProtoJsonUtil.fromJson(getBody(), aClass); } - throw new BadHttpResponseException(httpResponse.statusCode(), httpResponse.body()); + throw new BadHttpResponseException(httpResponse.statusCode(), getBody()); } public int streamSize() { return httpResponse.headers().firstValue("streamSize").map(Integer::valueOf).orElse(1); } + + private String getBody() { + try { + InputStream bodyStream = httpResponse.body(); + if (httpResponse.headers().firstValue("Content-Encoding").orElse("").equals("gzip")) { + bodyStream = new GZIPInputStream(bodyStream); + } + return new String(bodyStream.readAllBytes()); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } } private HttpRequest.BodyPublisher asJson(Object arg) throws IOException {