Caching of responses in HttpUrlConnection of android

2.1k Views Asked by At

In my app , i have implemented HttpResponseCache to cache the responses so that it could be used instead of hitting the server. For a particular api , the server returns the header Cache-Control as no-cache;must-revalidate. It has the header ETag also. The problem is the response of this api is not cached. As a result each time I request the api , server returns 200. Does no-cache,must-revalidate mean the response won't/shouldn't be cached ?

Please find below the request and response headers of the http request :

Request Headers :

GET HTTP/1.1 User-Agent Accept application/json Cache-Control max-age=0 Cookie
Host
Connection Keep-Alive Accept-Encoding gzip

Response Headers :

HTTP/1.1 200 OK Server Apache-Coyote/1.1 Cache-Control no-cache, must-revalidate ETag "c683a0301c68c566fcc706f5cd82f1f8" Content-Type application/json;charset=UTF-8 Transfer-Encoding chunked Content-Encoding gzip Vary Accept-Encoding Date Mon, 24 Feb 2014 04:44:03 GMT

Sending HTTP_GET request :

URL url = new URL(this.url);
HttpURLConnection conn = null;
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(timeout);
conn.setConnectTimeout(timeout);
conn.setInstanceFollowRedirects(true);
conn.setRequestProperty("User-Agent", this.userAgent);
conn.setUseCaches(true);
conn.setDefaultUseCaches(true);
conn.connect();
this.responseCode = conn.getResponseCode();
this.extractResponseHeaders(conn.getHeaderFields());
InputStream inputStream = null;
if (this.responseCode >= 400 ) {
    inputStream = conn.getErrorStream();
} else {
    inputStream = conn.getInputStream();
}
try {
    if(null != inputStream){
        this.response   =  convertToString(inputStream);
    }
} catch (JSONException e) {
    e.printStackTrace();
}
0

There are 0 best solutions below