Skip to content

Instantly share code, notes, and snippets.

@ericleong
Created January 5, 2016 21:00
Show Gist options
  • Save ericleong/71b4c9138bb7edd9ac35 to your computer and use it in GitHub Desktop.
Save ericleong/71b4c9138bb7edd9ac35 to your computer and use it in GitHub Desktop.
Method to simultaneously save and parse the response from an OkHttp ResponseBody.
@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