我使用OkhttpClient使用OkhttpClient 3.2
和Retrofit2
向服务器发送15秒长的视频,有时它可以正常工作但有时我会收到以下错误,这是非常不一致的。
java.net.SocketTimeoutException:timeout
以下是我将视频发送到服务器的代码
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());
}
});
}
在阅读了一些问题之后,我尝试将连接超时设置为如下所示的OkhttpClient,但仍然无法解决问题。
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();
我完全不知道这部分出了什么问题,有人请给我一些指导。 TQ
答案 0 :(得分:1)
尝试传递实际文件对象
file = new File(tasks.getImageUrl());
requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
sendVideo(body);
答案 1 :(得分:1)
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());
}
})
// Add below line to your okhttp client
.connectTimeout(60, TimeUnit.SECONDS)
.build();