From 5e1f44778a5506653306141950abbe5802999f3a Mon Sep 17 00:00:00 2001 From: alhudz Date: Tue, 23 Jun 2026 17:14:02 +0530 Subject: [PATCH] honour requested charset in okhttp response body reader --- .../main/java/feign/okhttp/OkHttpClient.java | 5 +++- .../java/feign/okhttp/OkHttpClientTest.java | 23 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/okhttp/src/main/java/feign/okhttp/OkHttpClient.java b/okhttp/src/main/java/feign/okhttp/OkHttpClient.java index 25a8b7f1b1..70508fad55 100644 --- a/okhttp/src/main/java/feign/okhttp/OkHttpClient.java +++ b/okhttp/src/main/java/feign/okhttp/OkHttpClient.java @@ -20,8 +20,10 @@ import feign.AsyncClient; import feign.Client; import feign.Request.ProtocolVersion; +import feign.Util; import java.io.IOException; import java.io.InputStream; +import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.Charset; import java.util.Collection; @@ -151,7 +153,8 @@ public Reader asReader() throws IOException { @Override public Reader asReader(Charset charset) throws IOException { - return asReader(); + Util.checkNotNull(charset, "charset should not be null"); + return new InputStreamReader(asInputStream(), charset); } }; } diff --git a/okhttp/src/test/java/feign/okhttp/OkHttpClientTest.java b/okhttp/src/test/java/feign/okhttp/OkHttpClientTest.java index 67765db03d..b623afd552 100644 --- a/okhttp/src/test/java/feign/okhttp/OkHttpClientTest.java +++ b/okhttp/src/test/java/feign/okhttp/OkHttpClientTest.java @@ -18,6 +18,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assumptions.assumeFalse; +import feign.Client; import feign.Feign; import feign.Feign.Builder; import feign.Headers; @@ -31,6 +32,7 @@ import java.util.Collections; import java.util.concurrent.TimeUnit; import okhttp3.mockwebserver.MockResponse; +import okio.Buffer; import org.assertj.core.data.MapEntry; import org.junit.jupiter.api.Test; @@ -137,6 +139,27 @@ public void canExceptCaseInsensitiveHeader() throws Exception { assumeFalse(false, "OkHTTP client do not support gzip compression"); } + @Test + void asReaderHonoursRequestedCharset() throws Exception { + // "café" encoded as ISO-8859-1: the trailing 0xE9 is not valid standalone UTF-8 + byte[] body = {'c', 'a', 'f', (byte) 0xE9}; + Buffer buffer = new Buffer().write(body); + server.enqueue(new MockResponse().setBody(buffer).addHeader("Content-Type", "text/plain")); + + Client client = new OkHttpClient(); + Request request = + Request.create( + Request.HttpMethod.GET, + "http://localhost:" + server.getPort(), + Collections.emptyMap(), + Request.Body.empty(), + null); + Response response = client.execute(request, new Request.Options()); + + assertThat(Util.toString(response.body().asReader(StandardCharsets.ISO_8859_1))) + .isEqualTo("café"); + } + public interface OkHttpClientTestInterface { @RequestLine("GET /")