How to pass Header in Retrofit 2.1.0 - java

Hi From last two I'm stuck with this retrofit any one please help me.I have tried so many method to pass header in retrofit could but i couldn't im using Retrofit 2.0.1
build.gradle
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'
compile 'com.squareup.okhttp:okhttp:2.7.2'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
And in
ApiClientHeader.jav
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class ApiClientHeader {
public static final String BASE_URL = "URL";
private static Retrofit retrofit = null;
public static Retrofit getClient(final String token) {
OkHttpClient okClient = new OkHttpClient.Builder()
.addInterceptor(
new Interceptor() {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.header("Authorization", "Bearer " + token)
.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
})
.build();
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
And In my
ApiInterface.java
#GET("profile")
Call<JsonObject> getProfile();
And In My Activity i am just calling function
private void getProfileData()
{
Singleton single = new Singleton();
String auth = single.getAuthorization();
Log.d("===========>>>>>>",auth);
ApiInterface apiService =
ApiClientHeader.getClient(auth).create(ApiInterface.class);
//showProgress(true);
Call<JsonObject> profileResponse = apiService.getProfile();
profileResponse.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
//showProgress(false);
Log.d("============>"," Call Request " +String.valueOf(call.request().toString()));
Log.d("============>", " Response code " + String.valueOf(response.code()));
// Log.d("============>", " Response Body " + String.valueOf(response.body().toString()));
if(response.code() == HttpURLConnection.HTTP_OK)
{
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
//showProgress(false);
Log.d("============>"," Call Request " +String.valueOf(call.request().toString()));
Log.d("============>"," Call Request " +String.valueOf(call.request().headers()));
Log.d("=======>", "Failure" + t.getMessage());
}
});
}
Still I am getting 403 Invalid acces.
Here i have not used any POJO class to send or receive data. Please help me.

You have to pass your authentication string like this
#GET("profile")
Call<JsonObject> getProfile((#Header("Authorization") String authorization))

#Headers({
"Accept: application/vnd.github.v3.full+json",
"User-Agent: Retrofit-Sample-App"
})
#GET("users/{username}")
Call<User> getUser(#Path("username") String username);
more info on documentation

I found one of the best link for Token based authentication using Retrofit 1.9 + OkHttp 2.4
You can add NetworkInterceptor, I have used it in my demo like:
httpClient.addNetworkInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
// Add authorization header with updated authorization value to intercepted request
Request authorisedRequest = originalRequest.newBuilder()
.header("Authorization", AccountAuthenticator.getAccessTokenWithTokenType(mContext))
.build();
return chain.proceed(authorisedRequest);
}
});
Dependencies:
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.google.code.gson:gson:2.8.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'
Thank you.

Try below code with your class, It is working for me:
final RestAdapter restAdapter = new RestAdapter.Builder().setClient(client).setLogLevel(RestAdapter.LogLevel.FULL).setRequestInterceptor(new RequestInterceptor() {
#Override
public void intercept(RequestFacade requestFacade) {
requestFacade.addHeader("key", "value");
requestFacade.addHeader("X-Requested-With", "XMLHttpRequest");
}
}).setConverter(new GsonConverter(gson)).setEndpoint(context.getString(R.string.base_url)).build();
Edit Post :
public class RestClient {
// private static final String BASE_URL = "http://api.plumperfect.com";
private WebServicesInterface apiService;
private static RestClient instance;
public RestClient(Context context) {
instance = this;
final Gson gson = new GsonBuilder().registerTypeAdapterFactory(new ItemTypeAdapterFactory()).setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'").create();
// final int cacheSize = 10 * 1024 * 1024; // 10 MiB
// final File cacheDirectory = new File(context.getCacheDir().getAbsolutePath(), "HttpCache");
// final OkHttpClient client = new OkHttpClient();
// Cache cache;
// try {
// cache = new Cache(cacheDirectory, cacheSize);
// client.setCache(cache);
// } catch (IOException e) {
// e.printStackTrace();
// }
final OkHttpClient okHttpClient = new OkHttpClient();
final Client client = new OkClient(okHttpClient);
final RestAdapter restAdapter = new RestAdapter.Builder().setClient(client).setLogLevel(RestAdapter.LogLevel.FULL).setRequestInterceptor(new RequestInterceptor() {
#Override
public void intercept(RequestFacade requestFacade) {
requestFacade.addHeader("key", "value");
requestFacade.addHeader("X-Requested-With", "XMLHttpRequest");
}
}).setConverter(new GsonConverter(gson)).setEndpoint(context.getString(R.string.base_url)).build();
apiService = restAdapter.create(WebServicesInterface.class);
}
public WebServicesInterface getApiService() {
return apiService;
}
public static RestClient getInstance() {
return instance;
}
}
Secound Class :
public class ItemTypeAdapterFactory implements TypeAdapterFactory {
#Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
return new TypeAdapter<T>() {
public void write(JsonWriter out, T value) throws IOException {
delegate.write(out, value);
}
public T read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
if (jsonElement.isJsonObject()) {
JsonObject jsonObject = jsonElement.getAsJsonObject();
if (jsonObject.has(Constants.DATA) && jsonObject.get(Constants.DATA).isJsonObject()) {
jsonElement = jsonObject.get(Constants.DATA);
}
}
return delegate.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}

Related

Retrofit interceptor with dagger2 timeout exception

I have an interceptor which works fine when i turn off internet it throw's the exception as expected but the problem occur when i turn on internet back again i get timeout exception.
AppModule.java
#Singleton
#Provides
Retrofit provideRetrofitInstance(RetrofitInterceptor retrofitInterceptor) {
return new Retrofit.Builder()
.baseUrl(BuildConfig.URL)
.client(new OkHttpClient()
.newBuilder()
.readTimeout(30, TimeUnit.SECONDS)
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.addInterceptor(retrofitInterceptor)
.build())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
#Provides
#Singleton
RetrofitInterceptor provideApiInterceptor(Context context) {
return new RetrofitInterceptor(context);
}
RetrofitInterceptor.java
public class RetrofitInterceptor implements Interceptor {
public static final String TAG = RetrofitInterceptor.class.getSimpleName();
private String sessionId;
private Context context;
#Inject
public RetrofitInterceptor(Context context) {
this.context = context;
}
#Override
public Response intercept(Chain chain) throws IOException {
if (NetworkUtils.isNetworkConnected(context)) {
Request request = chain.request();
Request.Builder requestBuilder = request.newBuilder();
if (sessionId != null) {
requestBuilder.header("sessionId", sessionId);
}
Response response = chain.proceed(requestBuilder.build());
return response;
} else {
throw new NoConnectivityException();
}
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
}

Why I am getting JsonSyntaxException Error

I am new to retrofit (I was using volley before), before this I was doing fine with retrofit until this error comes :-
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
Expected int but was Boolean at line 8 column 37 path
$.response.data.book_service_id
I tried with every solution provided in this site but could not help myself since I am new to retrofit.
I think it's because of the JSON parsing error. I don't know how to handle it.
This may be a duplicate question but please help.
Below is my code:
Request and fetching data:
private void makeBookingRequest(String position) {
final CustomProgressDialog dialog = new CustomProgressDialog();
dialog.show(getSupportFragmentManager(),"tag");
SharedPreferences preferences = getSharedPreferences("MYSharedPref",MODE_PRIVATE);
String sessionkey = preferences.getString("sessionkey",null);
System.out.println(sessionkey);
String serviceId = position;
System.out.println(position);
APIEndPoints endPoints = Url.getInstance().create(APIEndPoints.class);
Call<Book> call = endPoints.makeBookingRequest(serviceId,sessionkey);
call.enqueue(new Callback<Book>() {
#Override
public void onResponse(Call<Book> call, retrofit2.Response<Book> response) {
dialog.dismiss();
if (!response.isSuccessful()) {
Toast.makeText(HomeActivity.this, "server is not responding", Toast.LENGTH_SHORT).show();
}
else if(response.body() != null){
Book bookData = response.body();
String message = bookData.response.message;
Toast.makeText(HomeActivity.this, message, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Book> call, Throwable t) {
dialog.dismiss();
Toast.makeText(HomeActivity.this, "Error" + t.getLocalizedMessage(),
Toast.LENGTH_SHORT).show();
System.out.println(t);
}
});
}
Model Class:
package com.medpal.medpal_client.Models;
import com.google.gson.annotations.SerializedName;
public class Book {
#SerializedName("response")
public ResponseEntity response;
public class ResponseEntity{
#SerializedName("data")
public DataEntity data;
#SerializedName("secondary_message")
public String secondary_message;
#SerializedName("message")
public String message;
#SerializedName("code")
public int code;
}
public class DataEntity {
#SerializedName("book_service_id")
public int book_service_id;
}
}
APIENDPOINTS
#FormUrlEncoded
#Headers({"apikey: testapikey", "Content-Type:application/x-www-form-urlencoded" })
#POST("service/accept?")
Call<Book> makeBookingRequest(
#Field("service_id") String ServiceId,
#Field("session_key") String sessionKey);
URL class
public class Url {
public static final String base_url = "http://www.medpal.net/api/v1/";
public static final String serviceUrl = "http://www.medpal.net/api/v1/services?";
public static Retrofit retrofit;
public static Retrofit getInstance() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(base_url)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
Finallyy Response from server:
{
"response": {
"error": [],
"code": 200,
"message": "Service booked",
"secondary_message": "Service booked successfully",
"data": {
"book_service_id": 35
}
}
}
To detect the problem exactly, You need to use an interceptor to log the server response, to log the server responses you can use OkHttp3 here is an example of it.
private OkHttpClient provideOkhttpClient() {
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.readTimeout(15000, TimeUnit.MILLISECONDS);
client.writeTimeout(70000, TimeUnit.MILLISECONDS);
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
client.addInterceptor(interceptor);
return client.build();
}
And add this to your Retrofit.Builder
.client(provideOkhttpClient())
And these are for Gradle
implementation 'com.squareup.okhttp3:okhttp:3.12.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.5.0'
If you do this you will see everything you sent and got from the server at your Logcat.

How to fix Expected BEGIN_OBJECT but was STRING in Retrofit? [duplicate]

This question already has an answer here:
How to fix Expected BEGIN_OBJECT in Retrofit?
(1 answer)
Closed 4 years ago.
In my application i want use Retrofit for get some data from server.
I write below codes but when run application and call api show me below error :
E/socketLogResponse: Err : com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
Please see my above codes and help me
API response from server :
{
"status": "ok",
"time": 0.014972925186157227
}
ApiService interface :
#POST("api/log")
Call<SocketPingResponse> getSocketPingLog(#Header("jwt") String jwt, #Body SocketPingBodySendData socketPingBodySendData);
SocketPingResponse class :
public class SocketPingResponse {
#SerializedName("status")
#Expose
private String status;
#SerializedName("time")
#Expose
private Double time;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Double getTime() {
return time;
}
public void setTime(Double time) {
this.time = time;
}
}
SocketPingBodySendData class :
public class SocketPingBodySendData {
#SerializedName("auction_id")
#Expose
int auction_id;
#SerializedName("data")
#Expose
List<SocketPingEntity> data;
public int getAuction_id() {
return auction_id;
}
public void setAuction_id(int auction_id) {
this.auction_id = auction_id;
}
public List<SocketPingEntity> getData() {
return data;
}
public void setData(List<SocketPingEntity> data) {
this.data = data;
}
}
Api call codes in activity :
pingEntityList.addAll(socketPingDatabase.socketPingDao().getSocketPingEntityList());
SocketPingBodySendData pingBodySendData = new SocketPingBodySendData();
pingBodySendData.setAuction_id(auctionID);
pingBodySendData.setData(pingEntityList);
Toast.makeText(context, ""+pingEntityList.size(), Toast.LENGTH_SHORT).show();
Call<SocketPingResponse> pingResponseCall = apis.getSocketPingLog(jwtToken, pingBodySendData);
pingResponseCall.enqueue(new Callback<SocketPingResponse>() {
#Override
public void onResponse(Call<SocketPingResponse> call, Response<SocketPingResponse> response) {
if (response.body() != null) {
Toast.makeText(context, response.body().getStatus(), Toast.LENGTH_SHORT).show();
if (response.body().getStatus().equals("ok")) {
pingEntityList.clear();
socketPingDatabase.socketPingDao().deleteAll();
}
}
}
#Override
public void onFailure(Call<SocketPingResponse> call, Throwable t) {
Log.e("socketLogResponse", "Err : " + t.toString());
}
});
ApiClient class :
public class ApiClient {
private static final String BASE_URL = Constants.SERVER;
private static Retrofit retrofit = null;
private static Context context;
public static Retrofit getClient() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.interceptors().add(interceptor);
client.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder().addHeader("X-Client-Version", Constants.getAppVersionName()).build();
return chain.proceed(request);
}
});
client.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder().addHeader("uuid", Constants.getUUID(Constants.currentActivity)).build();
return chain.proceed(request);
}
});
client.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder().addHeader("agent", Constants.getAgent()).build();
return chain.proceed(request);
}
});
OkHttpClient client2 = client
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.build();
Gson gson = new GsonBuilder()
.setLenient()
.create();
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(client2)
.build();
}
return retrofit;
}
}
How can i fix this issue?
I think the problem returns string when no data is returned. Backend can usually do such errors. this error had happened to me before. you should check the response json when no data is available
Retrofit is typesafe library. It means that it waits only particular (predefined) types of objects. If server sends something else - it crashes with error. This is your case. Just check raw server response and you'll see what's wrong.
Try changing your API call
from
#POST("api/log")
Call<SocketPingResponse> getSocketPingLog(#Header("jwt") String jwt, #Body SocketPingBodySendData socketPingBodySendData);
to
#POST("api/log")
Call<String> getSocketPingLog(#Header("jwt") String jwt, #Body SocketPingBodySendData socketPingBodySendData);
pingEntityList.addAll(socketPingDatabase.socketPingDao().getSocketPingEntityList());
SocketPingBodySendData pingBodySendData = new SocketPingBodySendData();
pingBodySendData.setAuction_id(auctionID);
pingBodySendData.setData(pingEntityList);
Toast.makeText(context, ""+pingEntityList.size(), Toast.LENGTH_SHORT).show();
Call<String> pingResponseCall = apis.getSocketPingLog(jwtToken, pingBodySendData);
pingResponseCall.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.body() != null) {
//Convert here your string response to Other POJO format
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.e("socketLogResponse", "Err : " + t.toString());
}
});

Retrofit2 How to get redirect url #HEAD("/")

I have a minified URL and I want to have the final URL
With Retrofit 1.9 I used to do this :
#HEAD("/XXXXXXXXX")
void fetchFinalUrl(Callback<String> cb);
public void getUrl() {
mMinifyService.fetchFinalUrl(new Callback<String>() {
#Override
public void success(String s, Response response) {
response.getUrl();
}
[...]
}
But now with Retrofit 2 .getUrl() not exist any ideas how to do this?
Thanks in advance.
EDIT
Finally got it!
public class ApiProvider<T> {
private Retrofit retrofit;
private static final String END_POINT_MINIFY = "XXXXXXX";
public ApiProvider() {
initAdapter();
}
public T getService(Class<T> service) {
return retrofit.create(service);
}
private void initAdapter() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.followRedirects(false)
.build();
retrofit = new Retrofit.Builder()
.baseUrl(END_POINT_MINIFY)
.addConverterFactory(new ToStringConverterFactory())
.client(client)
.build();
}
}
public interface IMinifyService {
#HEAD("/XXXXXXXXX")
Call<Void> fetchFinalUrl(Callback<String> cb);
}
public class MinifyServiceImpl {
private ApiProvider<IMinifyService> mApiProvider = new ApiProvider<>();
private IMinifyService mMinifyService = mApiProvider.getService(IMinifyService.class);
public Promiser<String, Integer> fetchMinifyUrl() {
return new Promiser<>((resolve, reject) -> mMinifyService.fetchMinifyUrl().enqueue(new Callback<Void>() {
#Override
public void onResponse(Call<Void> call, Response<Void> response) {
if (response.code() >= 300 && response.code() < 400){
resole.run(response.headers().get("Location"));
} else {
reject.run(response.code());
}
}
#Override
public void onFailure(Call<Void> call, Throwable t) {
reject.run(t.hashCode());
}
}));
}
}
if you want to use Promizer --> Click here
response.raw().request().url()

Retrofit - Okhttp client How to cache the response

I'm trying to cache the response of http calls done by Retrofit(v 1.9.0) with OkHttp(2.3.0). It always made the network calls if I try to make a call without internet then java.net.UnknownHostException.
RestClient
public class RestClient {
public static final String BASE_URL = "http://something.example.net/JSONService";
private com.ucc.application.rest.ApiService apiService;
public RestClient() {
Gson gson = new GsonBuilder()
.setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'")
.create();
RequestInterceptor requestInterceptor = new RequestInterceptor() {
#Override
public void intercept(RequestFacade request) {
request.addHeader("Accept", "application/json");
int maxAge = 60 * 60;
request.addHeader("Cache-Control", "public, max-age=" + maxAge);
}
};
RestAdapter restAdapter = new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL)
.setEndpoint(BASE_URL)
.setClient(new OkClient(OkHttpSingleTonClass.getOkHttpClient()))
.setConverter(new GsonConverter(gson))
.setRequestInterceptor(requestInterceptor)
.build();
apiService = restAdapter.create(com.ucc.application.rest.ApiService.class);
}
public com.ucc.application.rest.ApiService getApiService() {
return apiService;
}
}
OkHttpSingleTonClass
public class OkHttpSingleTonClass {
private static OkHttpClient okHttpClient;
private OkHttpSingleTonClass() {
}
public static OkHttpClient getOkHttpClient() {
if (okHttpClient == null) {
okHttpClient = new OkHttpClient();
createCacheForOkHTTP();
}
return okHttpClient;
}
private static void createCacheForOkHTTP() {
Cache cache = null;
cache = new Cache(getDirectory(), 1024 * 1024 * 10);
okHttpClient.setCache(cache);
}
public static File getDirectory() {
final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "UCC" + File.separator);
root.mkdirs();
final String fname = UserUtil.CACHE_FILE_NAME;
final File sdImageMainDirectory = new File(root, fname);
return sdImageMainDirectory;
}
}
MyActivity
Request request = new Request.Builder()
.cacheControl(new CacheControl.Builder()
.onlyIfCached()
.maxAge(60 * 60, TimeUnit.SECONDS)
.build())
.url(RestClient.BASE_URL + Constants.GET_ABOUT_US_COLLECTION + "?userid=59e41b02-35ed-4962-8517-2668b5e8dae3&languageid=488d8f13-ef7d-4a3a-9516-0e0d24cbc720")
.build();
Log.d("url_request", RestClient.BASE_URL + Constants.GET_ABOUT_US_COLLECTION + "/?userid=10");
com.squareup.okhttp.Response forceCacheResponse = null;
try {
forceCacheResponse = OkHttpSingleTonClass.getOkHttpClient().newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
if (forceCacheResponse.code() != 504) {
// The resource was cached! Show it.
Log.d("From", "Local");
Toast.makeText(AboutUs.this, "Local", Toast.LENGTH_SHORT).show();
} else {
// The resource was not cached.
Log.d("From", "Network");
Toast.makeText(AboutUs.this, "Network", Toast.LENGTH_SHORT).show();
getAbouUsDetails();//This will use the Apiservice interface to hit the server.
}
I followed this. But I can't manage to work. Its simply hitting from the server. What am i doing wrong?
As per Retrofit 1.9.0 which uses OkClient does not have Caching support. We have to use OkHttpClient instance by Square OkHttpClient library.
You can compile by compile 'com.squareup.okhttp:okhttp:2.3.0'
Before everything retrofit caches by response headers like
Cache-Control:max-age=120,only-if-cached,max-stale
** 120 is seconds.
You can read more about headers here.
Caching headers are mostly instructed by server response. Try to implement cache headers in servers. If you don't have an option, yes retrofit has it.
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();
}
};
Where to cache:
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”);
}
Add interceptor to the OkHttpClient instance:
okHttpClient.networkInterceptors().add(REWRITE_CACHE_CONTROL_INTERCEPTOR);
And finally add OkHttpClient to the RestAdapter:
RestAdapter.setClient(new OkClient(okHttpClient));
And you can go through this slide for more reference.

Categories

Resources