I am using Retrofit 2.1.0 for API parsing in my android application. I need the time taken by retrofit to parse the API.
How to obtain the Request/ response time using Retrofit 2.
Below is the Retrofit Rest Client Call I am using for API parsing.
public static class ServiceGenerated {
static OkHttpClient httpClient = new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request.Builder ongoing = chain.request().newBuilder();
return chain.proceed(ongoing.build());
}
})
.build();
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(RetrofitUtils.API_BASE_URL)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create());
public static <S> S createService(Class<S> serviceClass) {
Retrofit retrofit = builder.client(httpClient).build();
return retrofit.create(serviceClass);
}
}
You can calculate the total round trip time by substracting the timestamp when response is received and timestamp when the request is sent. These two methods from the Response object will give you these two values
Response.sentRequestAtMillis()
Response.receivedResponseAtMillis()
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
long tx = response.sentRequestAtMillis();
long rx = response.receivedResponseAtMillis();
System.out.println("response time : "+(rx - tx)+" ms");
It's easy you can find the receivedResponseAtMillis() and the sendResponseAtMillis() in the raw() part of the response and then you can calculate the difference
response.raw().receivedResponseAtMillis()
response.raw().sendResponseAtMillis()
Try this
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(httpLoggingInterceptor);
}
also add
compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'
to your app module gradle file
Sample response:
Date: Fri, 12 Aug 2016 07:33:23 GMT
OkHttp-Sent-Millis: 1470987074283
OkHttp-Received-Millis: 1470987074422
Related
I am using retrofit to make a POST call to AWS server. It gives me the following error
Response{protocol=h2, code=403, message=, url=https://9oe8xt95sj.execute-api.ap-southeast-1.amazonaws.com/voip-dev-wa/staging/Device/registerCustomer}
My Retrofit method is as below
Retrofit retrofit;
retrofit = new Retrofit.Builder()
.baseUrl(ApiService.API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
apiService = retrofit.create(ApiService.class);
ApiService.java
String API_BASE_URL = "SOME String";
#POST("registerCustomer")
#Headers({"Content-Type: application/json", "accept: application/json"})
Call<RegisterResponse> register(#Body Register register);
How to solve this?
The problem is I did not pass the access token as the header. So it is responding forbidden error.
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request.Builder ongoing = chain.request().newBuilder();
ongoing.addHeader("Content-Type", "application/json");
ongoing.addHeader("accept", "application/json");
ongoing.addHeader("Authorization", "Bearer " + AppSetting.getInstance().getSDKDataManager().getAccessToken());
return chain.proceed(ongoing.build());
}
});
I have a strange problem with one of my retrofit call,it works fine when the app is in the background(recent list)
I have a call through which i update my widget data,the problem is when the app is cleared of from the recent list,the call gives HTTP 401 unauthorized response.
however i pass the same bearer token with it.
please have a look at the code and suggest some help
public static OkHttpClient getOkhttpClient() {
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request().newBuilder()
.addHeader("Authorization", "Bearer " + TokenGenerator.getToken())
.build();
return chain.proceed(newRequest);
}
}).build();
return client;
}
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(getOkhttpClient())
.addConverterFactory(JacksonConverterFactory.create())
.build();
}
return retrofit;
}
I am using Retrofit in an Android application. When I hit an API with token to get user information it gives cached(previous) response. Whenever I logged out and log in again API gives previous user detail, I tested API in Postman it works fine there.
I have tried some solutions I searched but nothing is working.
Response header that I am getting is
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Server: Kestrel
Date: Mon, 08 Jan 2018 09:35:26 GMT
Below is ApiClient class
public class ApiClient {
public static final String BASE_URL = "http://XX.XXX.XXX.XX/api/";
private static Retrofit authRetrofit = null;
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
}
return retrofit;
}
public static Retrofit getAuthorizeClient(final String token) {
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.addHeader("Authorization", "Bearer " + token)
.addHeader("Cache-control", "no-cache")
.method(original.method(), original.body())
//.cacheControl(CacheControl.FORCE_NETWORK)
.build();
return chain.proceed(request);
}
});
OkHttpClient client = httpClient.cache(null).build();
if (authRetrofit == null) {
authRetrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.client(client).build();
}
return authRetrofit;
}
}
In your httpClient interceptor, try adding cache control header:
.addHeader("Cache-control", "no-cache");
EDIT
Just noticed you are on Retrofit2
original.newBuilder().header("Cache-control", "no-cache");
Alternatively try adding it as an annotation to your API method:
#Headers("Cache-control: no-cache")
Response callApi();
According to Docs.
EDIT 2
Okay I suspect it's because of your if condition, your authRetrofit wouldn't be updated if condition failed. Try removing it
if (authRetrofit == null)
Help this helps.
Use Post request instead, I've faced the same problem, rectified by changing my GET method to post and send one random string as a Field.
im trying to consume an api that has that authorization header, i can get a 200 response in Postman with all data but cant get it to work in retrofit
May be you need add the Token using OkHttp Interceptor.
OkHttpClient client = new OkHttpClient.Builder()
.addNetworkInterceptor(mTokenInterceptor)
.build();
then add it to Retrofit:
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.baseUrl(base_url)
.build();
the mTokenInterceptor:
Interceptor mTokenInterceptor = new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (mToken != null) {
Request.Builder requestBuilder = request.newBuilder()
.addHeader("Authorization", mToken);
Request newRequest = requestBuilder.build();
return chain.proceed(newRequest);
}
return chain.proceed(request);
}
};
when you get the Token, just assign the mToken,
You can try something like below, just a crude example
#GET("your server url goes here")
Call<Your_Model_Class> getServerData(#Header("Authorization") String token);
Pass your token to getServerData method.
I want to add facebook access token into retrofit (2 beta 3) request, but the access token does not added.
I can add interceptor to retrofit 1.9 successfully but in retrofit 2 it has error, Is there any solution?
protected Retrofit getRestAdapter() {
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(
new Interceptor() {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
String sessionId = getSessionId(); // get access token
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.header("Cookie", sessionId)
.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
})
.build();
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl("http://tbkha.com/api/")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
}
return retrofit;
}
In retrofit retrofit 2.0 you add intercepter like this:
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(logging).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseURL)
.client(client)
.build();
Check this link for details https://futurestud.io/blog/retrofit-2-log-requests-and-responses
Similar questions:
App crash on HttpLoggingInterceptor
Retrofit2 HttpLoggingInterceptor Logcat