Skip to content

Commit

Permalink
Handle UnsupportedCharsetException in HttpLoggingInterceptor
Browse files Browse the repository at this point in the history
  • Loading branch information
dave-r12 committed Jan 16, 2016
1 parent c193481 commit fc238a2
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.concurrent.TimeUnit;
import okhttp3.Connection;
import okhttp3.Headers;
Expand Down Expand Up @@ -227,7 +228,15 @@ public Level getLevel() {
Charset charset = UTF8;
MediaType contentType = responseBody.contentType();
if (contentType != null) {
charset = contentType.charset(UTF8);
try {
charset = contentType.charset(UTF8);
} catch (UnsupportedCharsetException e) {
logger.log("");
logger.log("Couldn't decode the response body; charset is likely malformed.");
logger.log("<-- END HTTP");

return response;
}
}

if (contentLength != 0) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -598,6 +598,46 @@ private void bodyGetNoBody(int code) throws IOException {
.assertNoMoreLogs();
}

@Test public void bodyGetMalformedCharset() throws IOException {
setLevel(Level.BODY);

server.enqueue(new MockResponse()
.setHeader("Content-Type", "text/html; charset=0")
.setBody("Ignore This"));
Response response = client.newCall(request().build()).execute();
response.body().close();

networkLogs
.assertLogEqual("--> GET " + url + " http/1.1")
.assertLogEqual("Host: " + host)
.assertLogEqual("Connection: Keep-Alive")
.assertLogEqual("Accept-Encoding: gzip")
.assertLogMatch("User-Agent: okhttp/.+")
.assertLogEqual("--> END GET")
.assertLogMatch("<-- 200 OK " + url + " \\(\\d+ms\\)")
.assertLogEqual("Content-Type: text/html; charset=0")
.assertLogMatch("Content-Length: \\d+")
.assertLogMatch("OkHttp-Sent-Millis: \\d+")
.assertLogMatch("OkHttp-Received-Millis: \\d+")
.assertLogMatch("")
.assertLogEqual("Couldn't decode the response body; charset is likely malformed.")
.assertLogEqual("<-- END HTTP")
.assertNoMoreLogs();

applicationLogs
.assertLogEqual("--> GET " + url + " http/1.1")
.assertLogEqual("--> END GET")
.assertLogMatch("<-- 200 OK " + url + " \\(\\d+ms\\)")
.assertLogEqual("Content-Type: text/html; charset=0")
.assertLogMatch("Content-Length: \\d+")
.assertLogMatch("OkHttp-Sent-Millis: \\d+")
.assertLogMatch("OkHttp-Received-Millis: \\d+")
.assertLogEqual("")
.assertLogEqual("Couldn't decode the response body; charset is likely malformed.")
.assertLogEqual("<-- END HTTP")
.assertNoMoreLogs();
}

private Request.Builder request() {
return new Request.Builder().url(url);
}
Expand Down

0 comments on commit fc238a2

Please sign in to comment.