How to use disk cache to cache ParseFile - android

I'm using Parse and Picasso to load images onto ParseImageViews. Is there anything I'm missing to cache the parse files? My listview seems to be fetching the file from server every time and using the disk cache that comes with Picasso.
I don't see cache-control: max-age parameter in the http responses of downloads of parse files(from amazon s3 where parse stores them)
I have the following code,
final ParseImageView pic = viewHolder.img;
pic.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
ParseFile f = parseObject.getParseFile("image");
Picasso.with(mContext).load(f.getUrl()).into(pic);
Any help would be appreciated. Thanks.

Use OkHttp client as http transport for Picasso and specify disk and memory cache size:
OkHttpClient okHttp = new OkHttpClient();
Cache cache = new Cache(ctx.getCacheDir(), cacheSize);
okHttp.setCache(cache);
// Use OkHttp as downloader
Downloader downloader = new OkHttpDownloader(okHttp);
mPicasso = new Picasso.Builder(getApplicationContext())
.downloader(downloader)).memoryCache(new LruCache(size)).build();
Setup request interceptor (example) for OkHttp client:
// Add Cache-Control to origin response (force cache)
client.networkInterceptors().add(new Interceptor() {
private com.squareup.okhttp.Request request;
private Response response;
private String requestUrl;
#Override
public Response intercept(Chain c) throws IOException {
request = c.request();
response = c.proceed(request);
if (!request.cacheControl().noStore()
&& !response.cacheControl().noStore()) {
requestUrl = request.urlString();
// Do not cache keys or playlists
response = response
.newBuilder()
.header("Cache-Control","public, max-age=42000").build();
}
return response;
}
});

Related

How to use cache response for Retrofit with OkHttp when network response returns error

I have a simple use case: Use network response when success. Else use cached response.
But the problem is that when network response is an error, the cache is also written with that response.
One of the suggestions I read is to do FORCE_CACHE in the Interceptor when networkResponse is not successful.
But since the networkResponse overrides cache with error, next time when you request (and the server still returns an error), the cache will have an error.
Below is my current snippet. I need to add logic for returning cached value when networkResponse is an error. Any suggestion will be greatly helpful.
private void setup() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addInterceptor(REWRITE_CACHE_CONTROL);
File httpCacheDirectory = new File(context.getCacheDir(), "responses");
Cache cache = new Cache(httpCacheDirectory, 10 * 1024 * 1024); // 10 MB
builder.cache(cache);
}
private static final Interceptor REWRITE_CACHE_CONTROL = new Interceptor() {
#Override
public okhttp3.Response intercept(#NonNull Chain chain) throws IOException {
Request request = chain.request();
if (!hasAConnection()) {
request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
}
return chain.proceed(request);
}
};

How to make local test with okhttp

I am learning okhttp and I want to make a test with local json file in my computer or android device. But I don't know how to access local file as url string to call the function.
Like this:
File sdcard = Environment.getExternalStorageDirectory();
File testJson = new File(sdcard, "test.json");
HttpUtils.HttpGet(testJson., mCallback);
public class HttpUtils {
private static final String TAG = "HttpUtils";
private static final OkHttpClient mClient = new OkHttpClient();
public static void HttpGet(String url, Callback callback) {
//创建一个Request
final Request request = new Request.Builder()
.url(url)
.build();
//创建一个Call
Call call = mClient.newCall(request);
//请求加入调度
call.enqueue(callback);
}
}
You can use MockWebServer to serve content you load from a file.
https://github.com/square/okhttp/tree/master/mockwebserver
MockWebServer server = new MockWebServer();
// Schedule some responses.
server.enqueue(new MockResponse().setBody("hello, world!"));
server.enqueue(new MockResponse().setBody("sup, bra?"));
server.enqueue(new MockResponse().setBody("yo dog"));
// Start the server.
server.start();
// Ask the server for its URL. You'll need this to make HTTP requests.
HttpUrl baseUrl = server.url("/v1/chat/");
Well, you have to abstract your http client by some interface and create two implementation - one using OkHTTP and another - simply reading file.

Lazy load of images from server (post request) using Picasso [duplicate]

My API having some verification mechanism for every HTTP request. One of the end-point have the functionality to load a image using HTTP post method. The post request body will contain a JSON object which is verified from the server side.
For that i need to include a JSON like this on the http post request body.
{
"session_id": "someId",
"image_id": "some_id"
}
how can I do this with Picasso ?
I got the solution from the hint given by Mr.Jackson Chengalai.
Create a Okhttp request interceptor
private static class PicassoInterceptor implements Interceptor {
#Override
public Response intercept(Chain chain) throws IOException {
final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
Map<String, String> map = new HashMap<String, String>();
map.put("session_id", session_id);
map.put("image", image);
String requestJsonBody = new Gson().toJson(map);
RequestBody body = RequestBody.create(JSON, requestStringBody);
final Request original = chain.request();
final Request.Builder requestBuilder = original.newBuilder()
.url(url)
.post(body);
return chain.proceed(requestBuilder.build());
}
}
Create a Okhttp client add this interceptor
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.interceptors().add(new PicassoInterceptor());
Create a Dowloader using this okhttp client
OkHttpDownloader = downloader = new OkHttpDownloader(okHttpClient)
Build Picasso using this downloader
Picasso picasso = new Picasso.Builder(context).downloader(downloader ).build();

How to make use of cache data during offine in retrofit?

Am using retrofit 1.9 during offline i need to make use of cache response from server so how to create cache response in retrofit i have heard i can be done with okhttp but can somebody share snippet sample how to make use of cache response?
I am setting cache response like is this right way?
int cacheSize = 10 * 1024 *1024;
File cacheDirectory = new File(mcontext.getCacheDir().getAbsolutePath(), "HttpCache");
Cache cache = new Cache(cacheDirectory, cacheSize);
OkHttpClient client1 = new OkHttpClient();
client1.setCache(cache);
RestAdapter adapter = new RestAdapter.Builder().setEndpoint(url).setClient(new OkClient(client1)).build();
RetrofitRest retro = adapter.create(RetrofitRest.class);

How to configure the Http Cache when using Volley with OkHttp?

I want to try Volley combining with OkHttp but Volley cache system and OkHttp both rely on the HTTP cache as defined in the HTTP specification. So how can be disabled the cache of OkHttp for keeping one copy of HTTP cache?
EDIT: what I have done
public class VolleyUtil {
// http://arnab.ch/blog/2013/08/asynchronous-http-requests-in-android-using-volley/
private volatile static RequestQueue sRequestQueue;
/** get the single instance of RequestQueue **/
public static RequestQueue getQueue(Context context) {
if (sRequestQueue == null) {
synchronized (VolleyUtil.class) {
if (sRequestQueue == null) {
OkHttpClient client = new OkHttpClient();
client.networkInterceptors().add(new StethoInterceptor());
client.setCache(null);
sRequestQueue = Volley.newRequestQueue(context.getApplicationContext(), new OkHttpStack(client));
VolleyLog.DEBUG = true;
}
}
}
return sRequestQueue;
}
}
Which OkHttpClient is referenced from https://gist.github.com/bryanstern/4e8f1cb5a8e14c202750
OkHttp is a kind of HTTP client like HttpUrlConnection which implements HTTP cache, we can disable the cache of OkHttp like below:
OkHttpClient client = new OkHttpClient();
client.setCache(null);
Then, we can keep one copy of HTTP cache maintained by Volley.
IMPROVED:
I'd like to try to answer Sotti's questions.
1 I would like to know what is a good cache setup when using Volley and OkHttp.
In my project, i'm using one Volley requestQueue instance across all of restful APIs, and OkHttp worked as the transport layer for Volley like below.
public class VolleyUtil {
// http://arnab.ch/blog/2013/08/asynchronous-http-requests-in-android-using-volley/
private volatile static RequestQueue sRequestQueue;
/** get the single instance of RequestQueue **/
public static RequestQueue getQueue(Context context) {
if (sRequestQueue == null) {
synchronized (VolleyUtil.class) {
if (sRequestQueue == null) {
OkHttpClient client = new OkHttpClient();
client.setCache(null);
sRequestQueue = Volley.newRequestQueue(context.getApplicationContext(), new OkHttpStack(client));
VolleyLog.DEBUG = true;
}
}
}
return sRequestQueue;
}}
2 Should we rely on Volley or on the OkHttp cache?
Yes, i'm using Volley cache for my HTTP Cache instead of OkHttp Cache;
It works great for me.
3 What's the default behaviour out of the box?
For Volley:
it will create a "volley" default cache directory for you automatically.
/** Default on-disk cache directory. */
private static final String DEFAULT_CACHE_DIR = "volley";
public static RequestQueue newRequestQueue(Context context, HttpStack stack, int maxDiskCacheBytes) {
File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
……
}
For OkHttp:
i can't find the default cache in the source code, and we can set the response cache like this post
http://blog.denevell.org/android-okhttp-retrofit-using-cache.html
4. What's the recommended behaviour and how to achieve it?
As this post says:
Volley takes care of requesting, loading, caching, threading, synchronization and more. It’s ready to deal with JSON, images, caching, raw text and allow some customization.
I prefer to using Volley HTTP Cache because of the ease of customization.
For example, we can have much more control on the cache like this
Android Volley + JSONObjectRequest Caching.
The graceful way for OkHttp to ignore caches is:
request.setCacheControl(CacheControl.FORCE_NETWORK);

Categories

Resources