I am using the picasso
library to download the bitmap so in the api I need to pass the token in the headers. I tried below code from this thread Android Picasso library, How to add authentication headers?
public static Picasso getImageLoader(final Context context) {
// fetch the auth value
sSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
Picasso.Builder builder = new Picasso.Builder(context);
builder.downloader(new OkHttpDownloader(context) {
@Override
protected HttpURLConnection openConnection(Uri uri) throws IOException {
HttpURLConnection connection = super.openConnection(uri);
connection.setRequestProperty(Constant.HEADER_X_API_KEY, sSharedPreferences.getString(SharedPreferenceKeys.JSESSIONID, ""));
return connection;
}
});
sPicasso = builder.build();
return sPicasso;
}
mTarget = new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom loadedFrom) {
mdpImageView.setImageBitmap(bitmap);
Logger.d(TAG, "Test");
}
@Override
public void onBitmapFailed(Drawable drawable) {
Logger.d(TAG, "Test");
}
@Override
public void onPrepareLoad(Drawable drawable) {
Logger.d(TAG, "Test");
}
};
CustomPicasso.getImageLoader(getActivity()).with(getActivity()).load(URL).into(mTarget);
I debugged my code & I see it never called openconnection
override method of OkHttpDownloader
so my request always fail & at the end it calls onBitmapFailed
.
Please help what are things I have to do to pass headers value correctly.
Thanks in advance.
It took two days to resolve this problem. For custom downloader you don't have to call with
method because this will initialize the default downloader & picasso instance. Simply do below like this that will help you to get bitmap.
Picasso.Builder builder = new Picasso.Builder(getActivity());
picasso = builder.downloader(new OkHttpDownloader(getActivity()) {
@Override
protected HttpURLConnection openConnection(Uri uri) throws IOException {
HttpURLConnection connection = super.openConnection(uri);
connection.setRequestProperty(Constant.HEADER_X_API_KEY, mSharedPreferences.getString(SharedPreferenceKeys.JSESSIONID, ""));
return connection;
}
}).build();
picasso.load(url).into(mTarget);