Download Base64 Image On A Protected Site Using Picasso
I tried to use this Android Picasso library, How to add authentication headers? to access a protected image that returns the base64 version of the image. My problem is that the pic
Solution 1:
You need to intercept the answer and change it
OkHttpClient client;
OkHttpClient.Builder builderOkHttpClient;
builderOkHttpClient = newOkHttpClient.Builder();
builderOkHttpClient.addInterceptor(newInterceptor() {
@Overridepublic Response intercept(Chain chain)throws IOException {
RequestnewRequest= chain.request().newBuilder()
.build();
Responseresponse= chain.proceed(newRequest);
try {
MediaTypecontentType= response.body().contentType();
Stringbase64String= response.body().string().getBytes("UTF-8");
base64String = base64String .replace("data:image/jpeg;base64,", "");
byte[] decodedString = Base64.decode(base64String , Base64.DEFAULT);
ResponseBodybody= ResponseBody.create(contentType, decodedString);
response = response.newBuilder().body(body).build();
} catch (JSONException e) {
e.printStackTrace();
}
return response;
}
});
intcacheSize=10 * 1024 * 1024;
Cachecache=newCache(context.getCacheDir(), cacheSize);
builderOkHttpClient.cache(cache);
client = builderOkHttpClient.build();
Application.getAppComponent().inject(this);
picasso = newPicasso.Builder(context)
.downloader(newOkHttp3Downloader(client))
.loggingEnabled(true)
.indicatorsEnabled(true)
.listener(newPicasso.Listener() {
@OverridepublicvoidonImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
Log.e("PICASSO", "loading image " + uri);
Log.e("PICASSO ERROR", exception.getMessage());
}
}
).build();
Solution 2:
Above answer works great. Then if the base 64 encoded image is further stored inside a JSON Object.
String jsonData = response.body().string();
JSONObjectJobject = newJSONObject(jsonData);
String base64String = (String) Jobject.get("ImageData");
Post a Comment for "Download Base64 Image On A Protected Site Using Picasso"