Created
March 4, 2015 18:49
-
-
Save gouravd/628ba9781ffd5bda0c82 to your computer and use it in GitHub Desktop.
Retrofit read Response Body
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
package com.groupshoppy.helpers; | |
import java.io.ByteArrayOutputStream; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import retrofit.client.Response; | |
import retrofit.mime.MimeUtil; | |
import retrofit.mime.TypedByteArray; | |
import retrofit.mime.TypedInput; | |
/** | |
* Created by Gourav on 05-03-2015. | |
*/ | |
public class Utils { | |
private static final int BUFFER_SIZE = 0x1000; | |
public static String getBodyString(Response response) throws IOException { | |
TypedInput body = response.getBody(); | |
if (body!= null) { | |
if (!(body instanceof TypedByteArray)) { | |
// Read the entire response body to we can log it and replace the original response | |
response = readBodyToBytesIfNecessary(response); | |
body = response.getBody(); | |
} | |
byte[] bodyBytes = ((TypedByteArray) body).getBytes(); | |
String bodyMime = body.mimeType(); | |
String bodyCharset = MimeUtil.parseCharset(bodyMime); | |
return new String(bodyBytes, bodyCharset); | |
} | |
return null; | |
} | |
private static Response readBodyToBytesIfNecessary (Response response) throws IOException { | |
TypedInput body = response.getBody(); | |
if (body == null || body instanceof TypedByteArray) { | |
return response; | |
} | |
String bodyMime = body.mimeType(); | |
byte[] bodyBytes = streamToBytes(body.in()); | |
body = new TypedByteArray(bodyMime, bodyBytes); | |
return replaceResponseBody(response, body); | |
} | |
private static Response replaceResponseBody(Response response, TypedInput body) { | |
return new Response(response.getUrl(), response.getStatus(), response.getReason(), response.getHeaders(), body); | |
} | |
private static byte[] streamToBytes(InputStream stream) throws IOException { | |
ByteArrayOutputStream baos = new ByteArrayOutputStream(); | |
if (stream != null) { | |
byte[] buf = new byte[BUFFER_SIZE]; | |
int r; | |
while ((r = stream.read(buf)) != -1) { | |
baos.write(buf, 0, r); | |
} | |
} | |
return baos.toByteArray(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment