Cannot reach HTTP caching in android

I am trying to use OkHttp and Retrofit to cache HTTP requests. But I do not seem to understand why it does not work.

@Headers("Cache-Control: public, max-age=640000, s-maxage=640000 , max-stale=10000000") @FormUrlEncoded @POST("/news/getNewslist/") void newsListByGenre(@Field("news_genre") String genre, Callback<ArrayList<NewsStory>> callback); 

This is one of the queries, it contains all the necessary headers. Moreover, in an attempt to verify that something is written in File Cache, I manually assigned the OkHttpClient cache.

 OkHttpClient name = new OkHttpClient(); try { if (!cache.exists()) cache.createNewFile(); name.setResponseCache(new HttpResponseCache(cache, 10 * 1024 * 1024)); } catch (IOException e) { e.printStackTrace(); } 

The cache file I created contains only 36 bytes, so I’m sure that nothing is cached.

I also tried to make sure the server needed headers, although I want it to work without server intervention, but I also set the cache control headers in the request. This is a debug log from upgrades.

 null: HTTP/1.1 200 OK Cache-Control: public, max-age=360000 Connection: Keep-Alive Content-Length: 5167 Content-Type: application/json Date: Fri, 28 Jun 2013 01:00:22 GMT Keep-Alive: timeout=5, max=99 Server: Apache/2.4.3 (Win32) OpenSSL/1.0.1c PHP/5.4.7 X-Android-Received-Millis: 1372381311315 X-Android-Response-Source: NETWORK 200 X-Android-Selected-Transport: http/1.1 X-Android-Sent-Millis: 1372381311048 X-Powered-By: PHP/5.4.7 

I read the http caching mechanism over and over, but something seems to be missing.

+6
source share
2 answers

You cannot cache POST responses. Use the GET method instead. Here's a working example of Retrofit and OkHttp with caching:

https://gist.github.com/swankjesse/5889518

+8
source

@ Jess Wilson - I think it makes sense to cache the answer sometimes - I am working on an application that makes a network call, but if the user switches actions and returns, I would like to use the same data that the POST Response returned earlier. I know that I can use ORM and save mu objects, etc., It seems like it would be much easier to say that modify use the same answer.

0
source

Source: https://habr.com/ru/post/948286/


All Articles