I'm developing an app using Retrofit 2 to request to API. This API is in ASP.NET and it is zipping with GZip and encoding to Base64, like the code below:
private static string Compress(string conteudo)
{
Encoding encoding = Encoding.UTF8;
byte[] raw = encoding.GetBytes(conteudo);
using (var memory = new MemoryStream())
{
using (GZipStream gzip = new GZipStream(memory, CompressionMode.Compress, true))
{
gzip.Write(raw, 0, raw.Length);
}
return Convert.ToBase64String(memory.ToArray());
}
}
private static string Decompress(string conteudo)
{
Encoding encoding = Encoding.UTF8;
var gzip = Convert.FromBase64String(conteudo);
using (GZipStream stream = new GZipStream(new MemoryStream(gzip), CompressionMode.Decompress))
{
int size = gzip.Length;
byte[] buffer = new byte[size];
using (MemoryStream memory = new MemoryStream())
{
int count = 0;
do
{
count = stream.Read(buffer, 0, size);
if (count > 0)
{
memory.Write(buffer, 0, count);
}
}
while (count > 0);
return encoding.GetString(memory.ToArray());
}
}
}
Now, what I need to do in my Android app is get the response from Retrofit, decode from Base64 and unzip it. I tried to do it using Interceptor
, but I got no success.
This is the return that I received from the service H4sIAAAAAAAEACspKk0FAI1M/P0EAAAA
, decoding and unzipping the response, we have true
.
Does anybody know how to do it?
It's easy. The code below uses Google Guava in order to decode Base64 character streams and Google Gson to deserialize JSON content.
Consider the following test service interface:
Now you can implement your interceptor response input stream transformer base using the template method design pattern:
This implementation should also detect content MIME types in order not to do wrong transformations, but you can implement it yourself easily. So here are also two transforming interceptors for both Base64 and GZip:
And test it:
Note that
getFakeContentInterceptor
returns a fake interceptor that always returnsH4sIAAAAAAAEACspKk0FAI1M/P0EAAAA
so thatbaseUrl
does not even have a real URL. The output:Another way is to add Filter and modify the request / response objects with wrappers.
You can add a proxy layer (jetty proxy servlet org.eclipse.jetty.proxy.ProxyServlet) and override methods : onResponseContent, addProxyHeaders