Issue
Here is the code
public class InitializeBuilderOkhttp extends OkHttpClient{
OkHttpClient client;
public OkHttpClient InitializeBuilderOkhttp() {
client = new OkHttpClient();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(30, TimeUnit.MINUTES);
builder.readTimeout(30, TimeUnit.MINUTES);
builder.writeTimeout(30, TimeUnit.MINUTES);
client = builder.build();
return client;
}
}
As you can see, I have given 30 minutes as connect timeout, read timeout and write timeout.
I am initializing and declaring the above class
OkHttpClient client = new InitializeBuilderOkhttp();
in the oncreate method of the activity.
In the doInBackground method of async task class I am calling a rest api with the above okhttp client.
@Override
protected String doInBackground(String... params) {
RequestBody formBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("userId", userId)
.addFormDataPart("password", password)
.addFormDataPart("datatype", "app")
.build();
Request request = new Request.Builder()
.url(params[0])
.post(formBody)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
What is wrong with this code? Thanks for your time.
Note:- The timeout is 10000 ms or 10 secs which is the default timeout time for okhttp.After 10 secs the error is shown on the logcat.That is the timeout has not changed and it has remained the default value.
Solution
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.build();
Make client in this way and use seconds unit instead of minutes. It will work.Hope it will help you.Do let me know if it works :)
Answered By - Muhammad Saad Rafique
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.