use of com.github.lianjiatech.retrofit.spring.boot.exception.ReadResponseBodyException in project retrofit-spring-boot-starter by LianjiaTech.
the class RetrofitUtils method readResponseBody.
/**
* read ResponseBody as String
*
* @param response response
* @return ResponseBody String
* @throws IOException
*/
public static String readResponseBody(Response response) throws ReadResponseBodyException {
try {
Headers headers = response.headers();
if (bodyHasUnknownEncoding(headers)) {
return null;
}
ResponseBody responseBody = response.body();
if (responseBody == null) {
return null;
}
long contentLength = responseBody.contentLength();
BufferedSource source = responseBody.source();
// Buffer the entire body.
source.request(Long.MAX_VALUE);
Buffer buffer = source.getBuffer();
if (GZIP.equalsIgnoreCase(headers.get(CONTENT_ENCODING))) {
try (GzipSource gzippedResponseBody = new GzipSource(buffer.clone())) {
buffer = new Buffer();
buffer.writeAll(gzippedResponseBody);
}
}
Charset charset = UTF8;
MediaType contentType = responseBody.contentType();
if (contentType != null) {
charset = contentType.charset(UTF8);
}
if (contentLength != 0) {
return buffer.clone().readString(charset);
} else {
return null;
}
} catch (Exception e) {
throw new ReadResponseBodyException(e);
}
}
Aggregations