I using OkhttpClient to send a video with 15 seconds long to the server using OkhttpClient 3.2
and Retrofit2
,sometimes it work fine but sometimes I get the error below,which is very inconsistent.
java.net.SocketTimeoutException: timeout
Here is my code for sending the video up to server
private void sendVideoToServer( final String videoFilePath,final String api_key)
{
File videoFile = new File(videoFilePath);
RequestBody videoBody = RequestBody.create(MediaType.parse("video/*"), videoFile);
MultipartBody.Part vFile = MultipartBody.Part.createFormData("video", videoFile.getName(), videoBody);
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
okhttp3.Request.Builder ongoing = chain.request().newBuilder();
ongoing.addHeader("authorization", api_key);
return chain.proceed(ongoing.build());
}
})
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(AppConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient)
.build();
VideoInterface videoInterface = retrofit.create(VideoInterface.class);
Call<ResultObject> serverCom = videoInterface.sendVideoToServer(vFile);
serverCom.enqueue(new Callback<ResultObject>() {
@Override
public void onResponse(Call<ResultObject> call, retrofit2.Response<ResultObject> response) {
ResultObject result = response.body();
if(!TextUtils.isEmpty(result.getSuccess())){
Log.d("video Result " , result.getSuccess());
}
}
@Override
public void onFailure(Call<ResultObject> call, Throwable t) {
Log.d("video error",t.toString());
}
});
}
After reading some question,I tried to set the connection timeout to the OkhttpClient like below,but still cant solve the problem.
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
okhttp3.Request.Builder ongoing = chain.request().newBuilder();
ongoing.addHeader("authorization", api_key);
return chain.proceed(ongoing.build());
}
});
builder.connectTimeout(5, TimeUnit.MINUTES)
.writeTimeout(5, TimeUnit.MINUTES)
.readTimeout(5, TimeUnit.MINUTES);
OkHttpClient httpClient = builder.build();
I totally dont know what was doing wrong in this part,somebody please give me some guidance. Tq