Search in sources :

Example 1 with ReadResponseBodyException

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);
    }
}
Also used : Buffer(okio.Buffer) GzipSource(okio.GzipSource) ReadResponseBodyException(com.github.lianjiatech.retrofit.spring.boot.exception.ReadResponseBodyException) Headers(okhttp3.Headers) Charset(java.nio.charset.Charset) MediaType(okhttp3.MediaType) IOException(java.io.IOException) ReadResponseBodyException(com.github.lianjiatech.retrofit.spring.boot.exception.ReadResponseBodyException) ResponseBody(okhttp3.ResponseBody) BufferedSource(okio.BufferedSource)

Aggregations

ReadResponseBodyException (com.github.lianjiatech.retrofit.spring.boot.exception.ReadResponseBodyException)1 IOException (java.io.IOException)1 Charset (java.nio.charset.Charset)1 Headers (okhttp3.Headers)1 MediaType (okhttp3.MediaType)1 ResponseBody (okhttp3.ResponseBody)1 Buffer (okio.Buffer)1 BufferedSource (okio.BufferedSource)1 GzipSource (okio.GzipSource)1