android picasso library add token header - android

I have been breaking my brain on this one,
I am using Picasso library to load and download images from my server, but now I want to add a header in my download request and I cant seem to find a way of doing it. all i want to do is set a header like :
setHeader("Authorization", "Bearer " + token);
I use this header in any of my server requests, but cant find a way to add it to the picasso line.
Any help would be appreciated, Thanks!

Picasso uses OkHttp as engine , or it is possible to configure Picasso to use it, and since you have to set the header of the http request, you can use an Interceptor. E.g. this is my Interceptor to handle basic authentication:
private static class BasicAuthInterceptor implements Interceptor {
#Override
public Response intercept(Chain chain) throws IOException {
final Request original = chain.request();
final Request.Builder requestBuilder = original.newBuilder()
.header("Authorization", "Basic " + BASIC_AUTH_ENCODED)
.method(original.method(), original.body());
return chain.proceed(requestBuilder.build());
}
}
and the you add the Interceptor to OkHttp like
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.interceptors().add(new BasicAuthInterceptor());
Last step is to configure Picasso to use okHttpClient.
The Picasso's builder provide a method for it :
new Picasso.Builder(context).downloader(new OkHttpDownloader(okHttpClient)).build();
gradle dependencies:
compile 'com.squareup.okhttp3:okhttp:3.0.1'
compile 'com.squareup.picasso:picasso:2.5.0'

Related

How to consume URL with two '?' in retrofit

I am trying to use retrofit 2.3 in my Android App.
I have following url format :
www.test.com/api?url=a?response=json.
How this URL will be casted to QueryParam? For first part www.test.com/api will be my base URL then #Query("url") value but how to handle responsetype=json after second '?'
it should be possible to also add this as query parameter
e.g.:
Call<TestSiteResult> getTestSiteInfo(#Query("url") String yourUrl, #Query("response") String responseType)
If this response parameter is needed always you can also consider using an OkHttpClient for the HTTP connection (you can simply add it with the client(OkHttpClient) method of the Retrofit.Builder) which is responsible for intercepting URLs and append a certain parameter to your URL (e.g. i used this for the interception of api keys).
A LoggingInterceptor could look like this:
public class TestLoggingInterceptor implements Interceptor {
#Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
HttpUrl originalHttpUrl = original.url();
HttpUrl url = originalHttpUrl.newBuilder()
.addQueryParameter("response", "json")
.build();
Request.Builder requestBuilder = original.newBuilder();
.url(url);
Request request = requestBuilder.build;
return chain.proceed(request);
}
}
I hope this can help you.

How to add Basic Authentication in Picasso 2.5.2 with OkHttp 3.2.0

I am using picasso 2.5.2 library to download bitmap from remote server, the image url requires basic authentication in header.
i have tried the following SO ansers but none of them work with the latest picasso and OkHttp libraries.
Answer - 1
Answer - 2
Answer - 3
Thanks in advance.
Try configuring an OkHttp3 client with authenticator, depending on your scheme and situation:
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.authenticator(new Authenticator()
{
#Override
public Request authenticate(Route route, Response response) throws IOException
{
String credential = Credentials.basic("user", "pass");
return response.request().newBuilder()
.header("Authorization", credential)
.build();
}
})
.build();
Then, use that client in forming your Picasso object, but with okhttp3 you will have to use a OkHttp3Downloader instead, like so:
Picasso picasso = new Picasso.Builder(context)
.downloader(new OkHttp3Downloader(okHttpClient))
.build();
You can get the OkHttp3Downloader from https://github.com/JakeWharton/picasso2-okhttp3-downloader

Freso: How can I set the OK Http client?

So some images I request require an authentication header to be added
I am using Retrofit 2.0 which has this OkHttp client with a interceptor to add the user token to the header to every request
okHttpClient.interceptors().add(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request(); //Current Request
Request requestWithToken = null; //The request with the access token which we will use if we have one instead of the original
requestWithToken = originalRequest.newBuilder().addHeader(Constants.UrlParamConstants.HEADER_AUTHORIZATION,String.format(Constants.UrlParamConstants.HEADER_AUTHORIZATION_VALUE, MyApplication.getInstance().getUser().getApiToken())).build();
Response response = chain.proceed((requestWithToken != null ? requestWithToken : originalRequest)); //proceed with the request and get the response
return response;
}
});
I would like to know how can I set the same okHttp client instance for Fresco library.
I am aware that you need to add this dependency to use OkHttp with Fresco but how about setting the client?
compile "com.facebook.fresco:imagepipeline-okhttp:0.8.0+"
At the end of the day I just need to set authentication header for an image request
thanks for reading
http://frescolib.org/docs/using-other-network-layers.html
Context context;
OkHttpClient okHttpClient; // build on your own
ImagePipelineConfig config = OkHttpImagePipelineConfigFactory
.newBuilder(context, okHttpClient)
. // other setters
. // setNetworkFetcher is already called for you
.build();
Fresco.initialize(context, config);

Get redirected URL from Picasso

I'm fetching my images using the following code:
Picasso.with(mContext)
.load(myImage.getUrl())
.fetch();
myImage.getUrl() returns a URL from my server, which will redirect to the actual image hosted on another server. Is there a way to catch the URL my server returns to Picasso? I know I can use a Callback in .fetch(), but that's all I know. I'm using OkHttp as well.
OkHttp allows you not to follow redirects automatically:
OkHttpClient client = new OkHttpClient();
client.setFollowRedirects(false);
You can read the response, get the redirect URL and then forward it manually to Picasso.
EDIT:
Interceptors are feasible as well:
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
// process response here
return response;
}
});
I fixed it by this code.
val downloader = OkHttp3Downloader(context)
Picasso.Builder(context).downloader(downloader).build()
Check this for detail.
https://github.com/square/picasso/issues/463
Add okhttp dependency
compile 'com.squareup.okhttp:okhttp:2.5.0'
and try this code
Picasso.Builder builder = new Picasso.Builder(context);
builder.downloader(new OkHttpDownloader(context));
builder.build()
.load(path.trim())
.into(imageView);
This code working for me

Remove if-modified-since header from okhttp request

okhttp sends both if-modified-since date and if-none-match checksum headers in requests. There's usually no need for both and if-none-match is enough to figure out the version the client has. Sending both just confuses some http/1.1 server implementations
I have tried
builder = new Request.Builder().removeHeader("if-modified-since");
But that doesn't seem to do it. I assume the header is added later.
Is there a way to tell okhttp not to send if-modified-since ?
Yes. you can in builder.
You basically need to rebuild your request. Here is a complete sample:
httpClient.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request newRequest = chain
.request()
.newBuilder()
.removeHeader("if-modified-since")
.build();
return chain.proceed(newRequest);
}
});

Categories

Resources