I have seen other threads for this issue but unable to get any proper answer.
#POST("task/GetAllTasks")
Call<MyTask> getMyTasks(#Header("Authorization") String token, #Query("EmployeeId") String emp);
This is how I am calling, at first I thought it is due to GET request data limitation because GET imposes data limits and then I changed request from GET to POST but issue still persists.
ApiUtils.getTaskService().getMyTasks(apiToken, employeeId).enqueue(new Callback<MyTask>() {
#Override
public void onResponse(Call<MyTask> call, Response<MyTask> response) {
// ... Successful code goes here
}
#Override
public void onFailure(Call<MyTask> call, Throwable t) {
//.. This block of code executing now :(
}
}
Always onFailure is being called. I have tested this same request on Postman and it is returning data. Content-Length is content-length →45720
It does work on small amount of data as I have tested it on Dev database which has smaller amount of data but on Live environment it is continuously causing problem.
Please suggest a solution or should I leave Retrofit and move to native Android library for this?
EDIT: Can we increase request timeout in Retrofit, if yes then how?
Try to increase your timeout:
OkHttpClient client = new OkHttpClient().newBuilder()
.readTimeout(10, TimeUnit.SECONDS)
.connectTimeout(10, TimeUnit.SECONDS).build();
And set it to your retrofit:
new Retrofit.Builder().baseUrl("xxx").client(client).build().create(xxx.class);
Use #Part to send big string data it can easily send your data to server side
For ex.
You need to send some string that name is "abc" then in the retrofit code
#Part("abc") //your string variable
Its works for me and I save that data to mediumtext in mysql
and the code is $_REQUEST['abc'];
It is easy to say it's duplicate but it isn't.
I read many post about how to set the connection timeout in android but the post are 4-7 years old and I think that we all need an update about this topic because those methods are deprecated or no longer exist.
So the question is how can I set my connection timeout when I am waiting for a response from the server?
final Response response = httpClient.newCall(request).execute();
if (response.isSuccessful()) {
//success
} else {
//unsuccessful
}
If you create your OkHttpClient through an OkHttpClient.Builder, there are connectTimeout(), readTimeout(), and writeTimeout() methods that you can call for the various timeout options.
If you need to override them for a specific HTTP request, call newBuilder() on your OkHttpClient. That gives you an OkHttpClient.Builder with the same settings as you used originally. You can override those as needed, and create a temporary OkHttpClient from the new Builder, using that for this one-off call.
I am using retrofit for http calls in my Android application and retrofit.client.UrlConnectionClient as the client while building the adapter.
RestAdapter.Builder builder = new RestAdapter.Builder()
.setEndpoint(url)
.setLogLevel(RestAdapter.LogLevel.FULL)
.setClient(
new Client.Provider() {
public Client get() {
return new UrlConnectionClient() {
#Override
protected HttpURLConnection openConnection(Request request)
throws IOException {
HttpURLConnection connection = super.openConnection(request);
connection.setConnectTimeout(connectionTimeout);
return connection;
}
I wanted to set the timeout so I have used UrlConnectionClient as my client. I could not find a way with other clients like OkHttp.
Question is : How can I cancel the ongoing request ?.
I have seen a similar post # Using Square's Retrofit Client, is it possible to cancel an in progress request? If so how? but my code would get really complex if I try to add my own executors and try to cancel the request using that. I am looking if there is slightly a better way with my existing code.
I also see that Retorofit V2.0 has plan for Retry and Cancel but not sure when that would be released..https://github.com/square/retrofit/issues/297
Need help !
In fact I also need a way to retry with the same code.
This has been available since 2.0.0-beta2 (https://github.com/square/retrofit/releases/tag/parent-2.0.0-beta2). I don't know if there is a doc that explains that but here is the link to API:
http://square.github.io/retrofit/2.x/retrofit/retrofit/Call.html#cancel--
'Call' API allows to do Retry as well by 'Clone'ing the request.
I used Retrofit in order to make HTTP requests and JSON parsing and I loved the way to turn on debug logs. Logs allow to see body requests, URL... which is very useful. As Retrofit use OkHttp, I'm wondering if OkHttp also have a way to enable logs for each requests made.
Using an Interceptor, you can define the following class:
class LoggingInterceptor implements Interceptor {
#Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
Log.d("OkHttp", String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();
Log.d("OkHttp", String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers()));
return response;
}
}
And add it:
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.build();
The interceptors feature is currently in review, but you can build your own version of okHttp with the feature by applying the code changes in the pull request.
You can implement the functionality you want with something like this
// Create an interceptor which catches requests and logs the info you want
RequestInterceptor logRequests= new RequestInterceptor() {
public Request execute(Request request) {
Log.i("REQUEST INFO", request.toString());
return request; // return the request unaltered
}
};
OkHttpClient client = new OkHttpClient();
List<RequestInterceptor> requestInterceptors = client.requestInterceptors();
requestInterceptros.add(logRequests);
A test is included within the pull request if you want to see more.
I'm going to have to warn you ahead of time about using this. There may be changes to the interceptor API since it has yet to be merged in. Don't use it with production code, but it's innocuous enough for personal testing.
None yet. But there's an interceptors feature under development that should make it easy.
There's an official solution from Square (employee) now.
You can try:
https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor
for okhttp3
HttpLoggingInterceptor logging = new HttpLoggingInterceptor(message -> Log.d(YourClass.class.getSimpleName(), "OkHttp: " + message));
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
okHttpClient.getHttpClient().interceptors().add(logging);
you can enble logging and integerate with Timber to log only in debug.
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
#Override
public void log(String message) {
Timber.tag("OkHttp: ");
Timber.i(message);
}
}).setLevel(HttpLoggingInterceptor.Level.BODY);
client = new OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor)
.build();
I add some info regarding OkHttp3, because it supports logging out of the shelf.
First, be sure to have both these dependencies, the OkHttp3 main package and the specific package containing the logger implementations. Here I use 3.14.6.
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.6</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>logging-interceptor</artifactId>
<version>3.14.6</version>
</dependency>
Then set up your OkHttp client properly.
...
import okhttp3.logging.HttpLoggingInterceptor;
...
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(message -> logger.info(message));
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addNetworkInterceptor(interceptor)
.build();
The main idea is that you have to explain to the HttpLoggingInterceptor how to log, so in the above example the message is just routed to an Slf4j logger at INFO level.
For better ui and debugging of OkHttp Network calls you can use libraries like GANDER
Others features include :
Apps using Gander will display a notification showing a summary of ongoing HTTP activity. Tapping on the notification launches the full Gander UI. Apps can optionally suppress the notification, and launch the Gander UI directly from within their own interface. HTTP interactions and their contents can be exported via a share intent.
Search HTTP Activity and also request and response
The main Gander activity is launched in its own task, allowing it to be displayed alongside the host app UI using Android 7.x multi-window support.
Gander Provides following variants
Persistence : Saves logs to disk and TTL can be controlled
In Memory Database : Logs will be in memory as long as the app lifecycle.
No Op : This does nothing. So if users want Gander only in debug builds they can releaseCompile NoOp without dealing with variants, if(Build.DEBUG) ..etc
You can add logs by using:
public final OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new HttpLoggingInterceptor())
.cache(new Cache(cacheDir, cacheSize))
.build();
Which will use default config:
Logger DEFAULT = message -> Platform.get().log(INFO, message, null);
I am using retrofit to deserialize json request from web server and I need to create a session (cookie?) in my app (which should expire in 120 min). The problem is I don't know how to implement it.
private RestAdapter adapter = RestAdapter.Builder().setClient(????).setServer("http://192.168.0.1").build();
This session should persist only if the application is running.
Min SDK requirement is 8
Ok,you know the retrofit actually uses the okhttp inside the framework.
And you should know the "Interceptor"
When you init a okhttp in retrofit, you should invoke addInterceptor, just like this:
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.retryOnConnectionFailure(true);
builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
builder.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
builder.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
builder.addInterceptor(new ZCommonIntercepter());
Custom your own Intercepter extends Intercepter.
And get the sessionId by response.header("Set-cookie") save it as a Constant or something in your memory.
Every request after this you should remove the original header("cookie")
and addHeader (the thing that you have already saved)
I'm sorry that i'm not a native english speaker. If you can not understand me. I will just give you some keywords, you can google it.
---Key words---
interceptor in okhttp
cookies in request header or response header