Created
January 5, 2016 21:00
-
-
Save ericleong/71b4c9138bb7edd9ac35 to your computer and use it in GitHub Desktop.
Method to simultaneously save and parse the response from an OkHttp ResponseBody.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@SuppressWarnings({ "unchecked", "rawtypes" }) | |
private static <T> Pair<String, T> saveAndParseResponse(final ResponseBody response, final TypeReference type) | |
throws IOException { | |
final Buffer sink = new Buffer(); | |
final StringBuilder builder = new StringBuilder(); | |
final Charset charset = responseCharset(response); | |
response.source().readAll(new ForwardingSink(sink) { | |
@Override | |
public void write(final Buffer source, final long byteCount) throws IOException { | |
builder.append(new String(source.snapshot().toByteArray(), charset)); | |
super.write(source, byteCount); | |
} | |
}); | |
final Reader reader = new InputStreamReader(sink.inputStream(), charset); | |
try { | |
return new Pair<>(builder.toString(), (T) App.getObjectMapper().readValue(reader, type)); | |
} finally { | |
reader.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment