SlideShare une entreprise Scribd logo
1  sur  9
Retrofit Caching
- To Catch response by retrofit.
Prerequisites
Library dependencies
1. compile 'com.squareup.retrofit:retrofit:1.9.0'
2. compile 'com.squareup.okhttp:okhttp:2.3.0'
Why OkHttp?
Retrofit uses OkClient that doesn’t have support for
Caching. So we need to give custom OkHttpClient
instance.
Steps
1. Cache details to the OkHttpClient instance.
2. Caching is decided by server response headers.
3. If server response has no headers or we have to
change the headers. We can do that by Interceptors.
4. Set that to the OkHttpClient instance by
okHttpClient.networkInterceptors().add(interceptorInstance);
5. Set the OkClient instance by passing OkHttpClient
instance to the RestAdapter.
restAdapter.setClient(new OkClient(okHttpClient))
Warning!!
Its dangerous to change the server response
headers. Always try to give the headers in the server
response. For some extreme cases only try to implement
by ResponseInterceptors.
How its Caching?
Retrofit handles caching by the response Headers.
Cache-Control does the magic.
example
Cache-Control : max-age = 120, only-if-cached, max-
stale = 0
This header will cache the value for 120 seconds and also the api request will
try to check for the cache before trying to hit.
List of Cache-Control headers to play.
Cache Definition
private static void createCacheForOkHTTP() {
Cache cache = null;
cache = new Cache(getDirectory(), 1024 * 1024 * 10);
okHttpClient.setCache(cache);
}
//returns the file to store cached details
private File getDirectory() {
return new File(“location”);
}
Cache-Control Value
max-age - Timeout value in seconds to hit again.
no-cache - Do not use the cache.
no-store - Do not store the cache.
only-if-cached - Check the cache before trying to hit.
Change the response header values
private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new
Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.header("Cache-Control", String.format("max-age=%d, only-if-cached, max-
stale=%d", 120, 0))
.build();
}
};

Contenu connexe

Tendances

How To List Nginx Modules Installed / Complied on CentOS 7
How To List Nginx Modules Installed / Complied on CentOS 7How To List Nginx Modules Installed / Complied on CentOS 7
How To List Nginx Modules Installed / Complied on CentOS 7VCP Muthukrishna
 
Nginx bind() to 0.0.0.0:9080 failed
Nginx bind() to 0.0.0.0:9080 failedNginx bind() to 0.0.0.0:9080 failed
Nginx bind() to 0.0.0.0:9080 failedVCP Muthukrishna
 
How To Install and Configure SNMP on RHEL 7 or CentOS 7
How To Install and Configure SNMP on RHEL 7 or CentOS 7How To Install and Configure SNMP on RHEL 7 or CentOS 7
How To Install and Configure SNMP on RHEL 7 or CentOS 7VCP Muthukrishna
 
Writing Serverless Application in Java with comparison of 3 approaches: AWS S...
Writing Serverless Application in Java with comparison of 3 approaches: AWS S...Writing Serverless Application in Java with comparison of 3 approaches: AWS S...
Writing Serverless Application in Java with comparison of 3 approaches: AWS S...Andrew Zakordonets
 
How To Find Package Installation Date on RHEL 7
How To Find Package Installation Date on RHEL 7How To Find Package Installation Date on RHEL 7
How To Find Package Installation Date on RHEL 7VCP Muthukrishna
 
How to Change Hostname in CentOS 7 or RHEL 7
How to Change Hostname in CentOS 7 or RHEL 7How to Change Hostname in CentOS 7 or RHEL 7
How to Change Hostname in CentOS 7 or RHEL 7VCP Muthukrishna
 
How to Upgrade Openfire on CentOS 7
How to Upgrade Openfire on CentOS 7How to Upgrade Openfire on CentOS 7
How to Upgrade Openfire on CentOS 7VCP Muthukrishna
 
Salesforce interview questions on trigger
Salesforce interview questions on triggerSalesforce interview questions on trigger
Salesforce interview questions on triggerSumit Datta
 
Metasploit with postgresql_on_kali_linux_1.0.6
Metasploit with postgresql_on_kali_linux_1.0.6Metasploit with postgresql_on_kali_linux_1.0.6
Metasploit with postgresql_on_kali_linux_1.0.6Tinydile
 
salesforce triggers interview questions and answers
salesforce triggers interview questions and answerssalesforce triggers interview questions and answers
salesforce triggers interview questions and answersbhanuadmob
 
Install VMWare Tools CentOS 7
Install VMWare Tools CentOS 7Install VMWare Tools CentOS 7
Install VMWare Tools CentOS 7VCP Muthukrishna
 
How To Configure FirewallD on RHEL 7 or CentOS 7
How To Configure FirewallD on RHEL 7 or CentOS 7How To Configure FirewallD on RHEL 7 or CentOS 7
How To Configure FirewallD on RHEL 7 or CentOS 7VCP Muthukrishna
 
How To Install and Configure AWS CLI on RHEL 7
How To Install and Configure AWS CLI on RHEL 7How To Install and Configure AWS CLI on RHEL 7
How To Install and Configure AWS CLI on RHEL 7VCP Muthukrishna
 
ExecuteAndWait Interceptor
ExecuteAndWait InterceptorExecuteAndWait Interceptor
ExecuteAndWait InterceptorSeo Trainee
 
Batch script for nslookup range of ip address
Batch script for nslookup range of ip addressBatch script for nslookup range of ip address
Batch script for nslookup range of ip addressVCP Muthukrishna
 
BookKeeper Administrator's Guide
BookKeeper Administrator's GuideBookKeeper Administrator's Guide
BookKeeper Administrator's GuideJeff Smith
 

Tendances (20)

How To List Nginx Modules Installed / Complied on CentOS 7
How To List Nginx Modules Installed / Complied on CentOS 7How To List Nginx Modules Installed / Complied on CentOS 7
How To List Nginx Modules Installed / Complied on CentOS 7
 
Nginx bind() to 0.0.0.0:9080 failed
Nginx bind() to 0.0.0.0:9080 failedNginx bind() to 0.0.0.0:9080 failed
Nginx bind() to 0.0.0.0:9080 failed
 
How To Install and Configure SNMP on RHEL 7 or CentOS 7
How To Install and Configure SNMP on RHEL 7 or CentOS 7How To Install and Configure SNMP on RHEL 7 or CentOS 7
How To Install and Configure SNMP on RHEL 7 or CentOS 7
 
Writing Serverless Application in Java with comparison of 3 approaches: AWS S...
Writing Serverless Application in Java with comparison of 3 approaches: AWS S...Writing Serverless Application in Java with comparison of 3 approaches: AWS S...
Writing Serverless Application in Java with comparison of 3 approaches: AWS S...
 
How To Find Package Installation Date on RHEL 7
How To Find Package Installation Date on RHEL 7How To Find Package Installation Date on RHEL 7
How To Find Package Installation Date on RHEL 7
 
How to Change Hostname in CentOS 7 or RHEL 7
How to Change Hostname in CentOS 7 or RHEL 7How to Change Hostname in CentOS 7 or RHEL 7
How to Change Hostname in CentOS 7 or RHEL 7
 
How to Upgrade Openfire on CentOS 7
How to Upgrade Openfire on CentOS 7How to Upgrade Openfire on CentOS 7
How to Upgrade Openfire on CentOS 7
 
Salesforce interview questions on trigger
Salesforce interview questions on triggerSalesforce interview questions on trigger
Salesforce interview questions on trigger
 
Metasploit with postgresql_on_kali_linux_1.0.6
Metasploit with postgresql_on_kali_linux_1.0.6Metasploit with postgresql_on_kali_linux_1.0.6
Metasploit with postgresql_on_kali_linux_1.0.6
 
salesforce triggers interview questions and answers
salesforce triggers interview questions and answerssalesforce triggers interview questions and answers
salesforce triggers interview questions and answers
 
Install VMWare Tools CentOS 7
Install VMWare Tools CentOS 7Install VMWare Tools CentOS 7
Install VMWare Tools CentOS 7
 
Devstack
DevstackDevstack
Devstack
 
Who Broke My Crypto
Who Broke My CryptoWho Broke My Crypto
Who Broke My Crypto
 
How To Configure FirewallD on RHEL 7 or CentOS 7
How To Configure FirewallD on RHEL 7 or CentOS 7How To Configure FirewallD on RHEL 7 or CentOS 7
How To Configure FirewallD on RHEL 7 or CentOS 7
 
How To Install and Configure AWS CLI on RHEL 7
How To Install and Configure AWS CLI on RHEL 7How To Install and Configure AWS CLI on RHEL 7
How To Install and Configure AWS CLI on RHEL 7
 
Rdo mitaka
Rdo mitakaRdo mitaka
Rdo mitaka
 
ExecuteAndWait Interceptor
ExecuteAndWait InterceptorExecuteAndWait Interceptor
ExecuteAndWait Interceptor
 
Batch script for nslookup range of ip address
Batch script for nslookup range of ip addressBatch script for nslookup range of ip address
Batch script for nslookup range of ip address
 
BookKeeper Administrator's Guide
BookKeeper Administrator's GuideBookKeeper Administrator's Guide
BookKeeper Administrator's Guide
 
Openstack Neutron LBAAS
Openstack Neutron LBAAS Openstack Neutron LBAAS
Openstack Neutron LBAAS
 

Similaire à Retrofit Caching with OkHttp

Creating a MVC application hello world using tomcat 90 keep.pdf
Creating a MVC application hello world using tomcat 90 keep.pdfCreating a MVC application hello world using tomcat 90 keep.pdf
Creating a MVC application hello world using tomcat 90 keep.pdfaayushmaany2k14
 
My sql failover test using orchestrator
My sql failover test  using orchestratorMy sql failover test  using orchestrator
My sql failover test using orchestratorYoungHeon (Roy) Kim
 
Servletand sessiontracking
Servletand sessiontrackingServletand sessiontracking
Servletand sessiontrackingvamsi krishna
 
Altitude SF 2017: Debugging Fastly VCL 101
Altitude SF 2017: Debugging Fastly VCL 101Altitude SF 2017: Debugging Fastly VCL 101
Altitude SF 2017: Debugging Fastly VCL 101Fastly
 
I Need Serious Help with this assignment. Plenty Points to be earned.pdf
I Need Serious Help with this assignment. Plenty Points to be earned.pdfI Need Serious Help with this assignment. Plenty Points to be earned.pdf
I Need Serious Help with this assignment. Plenty Points to be earned.pdfahntagencies
 
Building resilient applications
Building resilient applicationsBuilding resilient applications
Building resilient applicationsNuno Caneco
 
Netty 4-based RPC System Development
Netty 4-based RPC System DevelopmentNetty 4-based RPC System Development
Netty 4-based RPC System DevelopmentAllan Huang
 
When it Absolutely, Positively, Has to be There: Reliability Guarantees in Ka...
When it Absolutely, Positively, Has to be There: Reliability Guarantees in Ka...When it Absolutely, Positively, Has to be There: Reliability Guarantees in Ka...
When it Absolutely, Positively, Has to be There: Reliability Guarantees in Ka...confluent
 
Production Ready Kafka on Kubernetes (Devandra Tagare, Lyft) Kafka Summit SF ...
Production Ready Kafka on Kubernetes (Devandra Tagare, Lyft) Kafka Summit SF ...Production Ready Kafka on Kubernetes (Devandra Tagare, Lyft) Kafka Summit SF ...
Production Ready Kafka on Kubernetes (Devandra Tagare, Lyft) Kafka Summit SF ...confluent
 
Jetty Continuation - 이상민
Jetty Continuation - 이상민Jetty Continuation - 이상민
Jetty Continuation - 이상민JavaCommunity.Org
 
Kubernetes Probes (Liveness, Readyness, Startup) Introduction
Kubernetes Probes (Liveness, Readyness, Startup) IntroductionKubernetes Probes (Liveness, Readyness, Startup) Introduction
Kubernetes Probes (Liveness, Readyness, Startup) IntroductionAkhmadZakiAlsafi
 
06 response-headers
06 response-headers06 response-headers
06 response-headerssnopteck
 
Bluestore oio adaptive_throttle_analysis
Bluestore oio adaptive_throttle_analysisBluestore oio adaptive_throttle_analysis
Bluestore oio adaptive_throttle_analysis병수 박
 
Chef cookbooks for OpenStack HA
Chef cookbooks for OpenStack HAChef cookbooks for OpenStack HA
Chef cookbooks for OpenStack HAAdam Spiers
 

Similaire à Retrofit Caching with OkHttp (20)

Hackingtomcat
HackingtomcatHackingtomcat
Hackingtomcat
 
Hacking Tomcat
Hacking TomcatHacking Tomcat
Hacking Tomcat
 
Creating a MVC application hello world using tomcat 90 keep.pdf
Creating a MVC application hello world using tomcat 90 keep.pdfCreating a MVC application hello world using tomcat 90 keep.pdf
Creating a MVC application hello world using tomcat 90 keep.pdf
 
My sql failover test using orchestrator
My sql failover test  using orchestratorMy sql failover test  using orchestrator
My sql failover test using orchestrator
 
Servletand sessiontracking
Servletand sessiontrackingServletand sessiontracking
Servletand sessiontracking
 
Altitude SF 2017: Debugging Fastly VCL 101
Altitude SF 2017: Debugging Fastly VCL 101Altitude SF 2017: Debugging Fastly VCL 101
Altitude SF 2017: Debugging Fastly VCL 101
 
I Need Serious Help with this assignment. Plenty Points to be earned.pdf
I Need Serious Help with this assignment. Plenty Points to be earned.pdfI Need Serious Help with this assignment. Plenty Points to be earned.pdf
I Need Serious Help with this assignment. Plenty Points to be earned.pdf
 
Building resilient applications
Building resilient applicationsBuilding resilient applications
Building resilient applications
 
Netty 4-based RPC System Development
Netty 4-based RPC System DevelopmentNetty 4-based RPC System Development
Netty 4-based RPC System Development
 
Dropped image 170
Dropped image 170Dropped image 170
Dropped image 170
 
When it Absolutely, Positively, Has to be There: Reliability Guarantees in Ka...
When it Absolutely, Positively, Has to be There: Reliability Guarantees in Ka...When it Absolutely, Positively, Has to be There: Reliability Guarantees in Ka...
When it Absolutely, Positively, Has to be There: Reliability Guarantees in Ka...
 
Servlets lecture2
Servlets lecture2Servlets lecture2
Servlets lecture2
 
Production Ready Kafka on Kubernetes (Devandra Tagare, Lyft) Kafka Summit SF ...
Production Ready Kafka on Kubernetes (Devandra Tagare, Lyft) Kafka Summit SF ...Production Ready Kafka on Kubernetes (Devandra Tagare, Lyft) Kafka Summit SF ...
Production Ready Kafka on Kubernetes (Devandra Tagare, Lyft) Kafka Summit SF ...
 
Jetty Continuation - 이상민
Jetty Continuation - 이상민Jetty Continuation - 이상민
Jetty Continuation - 이상민
 
JavaCro'15 - Spring @Async - Dragan Juričić
JavaCro'15 - Spring @Async - Dragan JuričićJavaCro'15 - Spring @Async - Dragan Juričić
JavaCro'15 - Spring @Async - Dragan Juričić
 
Kubernetes Probes (Liveness, Readyness, Startup) Introduction
Kubernetes Probes (Liveness, Readyness, Startup) IntroductionKubernetes Probes (Liveness, Readyness, Startup) Introduction
Kubernetes Probes (Liveness, Readyness, Startup) Introduction
 
06 response-headers
06 response-headers06 response-headers
06 response-headers
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Bluestore oio adaptive_throttle_analysis
Bluestore oio adaptive_throttle_analysisBluestore oio adaptive_throttle_analysis
Bluestore oio adaptive_throttle_analysis
 
Chef cookbooks for OpenStack HA
Chef cookbooks for OpenStack HAChef cookbooks for OpenStack HA
Chef cookbooks for OpenStack HA
 

Dernier

Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 

Dernier (20)

Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 

Retrofit Caching with OkHttp

  • 1. Retrofit Caching - To Catch response by retrofit.
  • 2. Prerequisites Library dependencies 1. compile 'com.squareup.retrofit:retrofit:1.9.0' 2. compile 'com.squareup.okhttp:okhttp:2.3.0'
  • 3. Why OkHttp? Retrofit uses OkClient that doesn’t have support for Caching. So we need to give custom OkHttpClient instance.
  • 4. Steps 1. Cache details to the OkHttpClient instance. 2. Caching is decided by server response headers. 3. If server response has no headers or we have to change the headers. We can do that by Interceptors. 4. Set that to the OkHttpClient instance by okHttpClient.networkInterceptors().add(interceptorInstance); 5. Set the OkClient instance by passing OkHttpClient instance to the RestAdapter. restAdapter.setClient(new OkClient(okHttpClient))
  • 5. Warning!! Its dangerous to change the server response headers. Always try to give the headers in the server response. For some extreme cases only try to implement by ResponseInterceptors.
  • 6. How its Caching? Retrofit handles caching by the response Headers. Cache-Control does the magic. example Cache-Control : max-age = 120, only-if-cached, max- stale = 0 This header will cache the value for 120 seconds and also the api request will try to check for the cache before trying to hit. List of Cache-Control headers to play.
  • 7. Cache Definition private static void createCacheForOkHTTP() { Cache cache = null; cache = new Cache(getDirectory(), 1024 * 1024 * 10); okHttpClient.setCache(cache); } //returns the file to store cached details private File getDirectory() { return new File(“location”); }
  • 8. Cache-Control Value max-age - Timeout value in seconds to hit again. no-cache - Do not use the cache. no-store - Do not store the cache. only-if-cached - Check the cache before trying to hit.
  • 9. Change the response header values private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .header("Cache-Control", String.format("max-age=%d, only-if-cached, max- stale=%d", 120, 0)) .build(); } };