aboutsummaryrefslogtreecommitdiffstats
path: root/AndroidAsyncSample/src/com/koushikdutta/async/sample/middleware/CacheOverrideMiddleware.java
blob: 86d65ff17efacd46ca7a5baf2200bad44442553f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.koushikdutta.async.sample.middleware;

import android.text.TextUtils;
import android.util.Base64;

import com.koushikdutta.async.http.AsyncHttpClient;
import com.koushikdutta.async.http.AsyncHttpClientMiddleware;
import com.koushikdutta.async.http.SimpleMiddleware;

import java.util.Hashtable;

/**
 * Created by koush on 2/15/15.
 */
public class CacheOverrideMiddleware extends SimpleMiddleware {
    // insert this using
    public static CacheOverrideMiddleware add(AsyncHttpClient client) {
        CacheOverrideMiddleware ret = new CacheOverrideMiddleware();
        // add this first so it gets called before everything else
        client.getMiddleware().add(0, ret);
        return ret;
    }

    @Override
    public void onHeadersReceived(OnHeadersReceivedDataOnRequestSentData data) {
        super.onHeadersReceived(data);

        // do more checking here, since uri may not necessarily be http or have a host, etc.
        String cache = cacheHeaders.get(data.request.getUri().getHost());
        if (!TextUtils.isEmpty(cache))
            data.request.setHeader("Cache-Control", cache);
    }

    Hashtable<String, String> cacheHeaders = new Hashtable<String, String>();

    /**
     * Override cache-control directives
     * @param host
     * @param cacheControl a Cache-Control value, like "max-age=300" to cache for 5 minutes
     */
    public void setCacheControlForHost(String host, String cacheControl) {
        cacheHeaders.put(host, cacheControl);
    }
}