I need to pass a header when I try to show a image using Picasso.
Can any one suggest how to add header to picasso while viewing the image.
You can use downloader for that:
https://github.com/JakeWharton/picasso2-okhttp3-downloader
Example:
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request().newBuilder()
.addHeader("custom-header", "custom-header-value")
.build();
return chain.proceed(newRequest);
}
})
.build();
Picasso picasso = new Picasso.Builder(context)
.downloader(new OkHttp3Downloader(client))
.build();
Keep in mind that if you are using OkHttpClient already, you should use that instance or create new one using client.newBuilder(). This way, both instances will be using the same request queue.
Related
I am developing an Android application which is displaying lots of images. I am using Picasso for loading the image and using its default caching strategy. Now what I want is to modify the caching and suppose if user has seen an image today it will be there in the cache for next seven days and each time user visit that particular page Picasso load the image from cache, after 7 days the image will be cleared from cache and do a fresh caching again. Someone, please help me I am lost.
private void PicassoConfig() {
Picasso.Builder builder = new Picasso.Builder(this);
builder.downloader(new OkHttp3Downloader (this, Constants.MAX_DISK_CACHE_SIZE));
Picasso built = builder.build();
Picasso.setSingletonInstance(built);
}
then
Picasso.get().load(cardList.get(i).
getImage()).noFade().priority(Picasso.Priority.HIGH).
placeholder(R.drawable.placehoder_image).
transform(new com.squareup.picasso.Transformation()
I want the image to be in the cache for a week.
Create a custom OkHttp interceptor and add to Picasso.
public Interceptor provideCacheInterceptor(final int maxDays) {
return new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
CacheControl cacheControl = new CacheControl.Builder()
.maxAge(maxDays, TimeUnit.DAYS)
.build();
return response.newBuilder()
.header(Constants.CACHE_CONTROL, cacheControl.toString())
.build();
}
};
}
Now, Add this to Gradle
compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.0.2'
Now attach Custom OkHttpClient to Picasso. More info here
okhttp3.OkHttpClient okHttp3Client = new okhttp3.OkHttpClient();
int MaxCacheDays = 7;
okHttp3Client.addNetworkInterceptor(provideCacheInterceptor(MaxCacheDays));
OkHttp3Downloader okHttp3Downloader = new OkHttp3Downloader(okHttp3Client);
Picasso picasso = new Picasso.Builder(context)
.downloader(new CustomOkHttp3Downloader(client))
.build();
I am using Picasso to download images and show them from the server. I need to set basic Aucathention to my requests. And because of that i used this:
'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0'
and my code is:
String url = "images/download/" + images.getiId();
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request().newBuilder()
.addHeader("user_auth", user_auth)
.addHeader("user_password", user_pass)
.build();
return chain.proceed(newRequest);
}
})
.build();
Picasso picasso = new Picasso.Builder(context)
.downloader(new OkHttp3Downloader(client))
.build();
picasso.load(url)
.error(R.drawable.error_icon_128)
.into(view);
}
but every time it can't download images And I can't see response code from the server. How can I see response code?
Thank you.
Does anyone know in Android How to use Okhttpclient Create a Http Delete Or Put Method With Params?
Using java , this is what i have tried:
CookieJarImpl cookieJar = new CookieJarImpl(new PersistentCookieStore(context));
okHttpClient = new OkHttpClient.Builder()
.cookieJar(cookieJar)
.addInterceptor(new LoggerInterceptor("TAG"))
.connectTimeout(10000L, TimeUnit.MILLISECONDS)
.readTimeout(10000L, TimeUnit.MILLISECONDS) //其他配置
.build();
You can build a URL with query parameters using the HttpUrl class. Then you can use an okhttp3.Request.Buidler() along with either the post() or delete() methods:
HttpUrl url = new HttpUrl.Builder()
.host(host).addQueryParameter(name, value).build();
Request request = new Request.Builder()
.url(url).post(RequestBody.create(mediaType, body)).addHeader(type, header).build();
okhttpClient.newCall(request).enqueue(new Callback() {
...
});
You can check out the OkHttp wiki for recipes if you need further help. Or you could use Square's other wonderful library, Retrofit, which pairs well with OkHttp.
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
I'm just learning Retrofit and OKHttp, now I have an issue.
Every request in my app is POST, just like this:
#FormUrlEncoded
#POST("some url")
Observable<Result> getData(#Field("id") String id);
In every POST, there are two same params. So in a most simple way, I can add two more #Field in every method, for example, #Field("token"),#Field("account"). But I think there must be a smart way.
Then I thought OkHttpClient may solve this.
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RequestBody body = new FormBody.Builder().add("account", "me")
.add("token", "123456").build();
request = request.newBuilder().post(body).build();
return chain.proceed(request);
}
}).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("some base url")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
Or
HttpUrl url = request.url().newBuilder()
.setEncodedQueryParameter("account", "me")
.setEncodedQueryParameter("token", "123456")
.build();
The first method just replace all Field to these two.
The second method just add these two as GET parameters, not POST.
Now I have absolutely no idea how to make this work.
OK...Finally I find a way to do this. But I'm not sure this is the best way.
Here is the code:
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
FormBody.Builder bodyBuilder = new FormBody.Builder();
FormBody b = (FormBody) request.body();
for (int i=0;i<b.size();i++) {
bodyBuilder.addEncoded(b.name(i),b.value(i));
}
bodyBuilder.addEncoded("account", "me").add("token", "123456");
request = request.newBuilder().post(bodyBuilder.build()).build();
return chain.proceed(request);
}
}).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://some url)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
I get all the #Field from retrofit, then add every key-value params to a new RequestBody, same as these two default params. Now every POST request has "account" and "token".
If there is a better way to do this, please let me know.
You can do that by adding a new request interceptor to the OkHttpClient. Intercept the actual request and get the HttpUrl. The http url is required to add query parameters since it will change the previously generated request url by appending the query parameter name and its value.
OkHttpClient.Builder httpClient =
new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
HttpUrl originalHttpUrl = original.url();
HttpUrl url = originalHttpUrl.newBuilder()
.addQueryParameter("apikey", "your-actual-api-key")
.build();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.url(url);
Request request = requestBuilder.build();
return chain.proceed(request);
}
});