SlideShare ist ein Scribd-Unternehmen logo
1 von 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();
}
};

Weitere ähnliche Inhalte

Was ist angesagt?

BookKeeper Administrator's Guide
BookKeeper Administrator's GuideBookKeeper Administrator's Guide
BookKeeper Administrator's Guide
Jeff Smith
 

Was ist angesagt? (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
 

Ähnlich wie Retrofit caching V1.9.0 - Android OkClient

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
aayushmaany2k14
 
Servletand sessiontracking
Servletand sessiontrackingServletand sessiontracking
Servletand sessiontracking
vamsi krishna
 
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
ahntagencies
 
Netty 4-based RPC System Development
Netty 4-based RPC System DevelopmentNetty 4-based RPC System Development
Netty 4-based RPC System Development
Allan Huang
 
06 response-headers
06 response-headers06 response-headers
06 response-headers
snopteck
 

Ähnlich wie Retrofit caching V1.9.0 - Android OkClient (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
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 

Retrofit caching V1.9.0 - Android OkClient

  • 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(); } };