无法停止更新发送

时间:2019-01-09 15:18:10

标签: java android sockets retrofit2 okhttp3

我使用改造和OkHttp3库向服务器发送一些消息,并将其设置如下:

okClient = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(15,TimeUnit.SECONDS)
                .addInterceptor(interceptor)
                .build();

当我要发送大消息时(例如,大约需要2分钟),Retrofit会完全发送我的文件,两分钟后,我收到TimeOut消息。如果我希望15秒后停止发送并显示错误消息。

是否有我必须遵守的特定项目?请引导我。

或者建议我一种在15秒后中断此操作的标准方法。

mycode:

class RetrofitFactory {
private static final RetrofitFactory INSTANCE = new RetrofitFactory();
public static RetrofitFactory getInstance() {
    return INSTANCE;
}

public OkHttpClient getOkHttp()
{
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    okClient = new OkHttpClient.Builder()
            .connectTimeout(15, TimeUnit.SECONDS)
            .readTimeout(15, TimeUnit.SECONDS)
            .writeTimeout(15,TimeUnit.SECONDS)
            .addInterceptor(new GzipRequestInterceptor())
            .addInterceptor(interceptor)
            .build();
    return okClient;
}

public myInterface getlimit()
{
    if (retrofit == null) {
            OkHttpClient okClient = getOkHttp();
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            retrofit = new Retrofit.Builder()
                    .client(okClient)
                    .baseUrl(BuildConfig.BASEURL)
                    .addConverterFactory(JacksonConverterFactory.create(objectMapper))
                    .build();
    }

    return retrofit.create(myInterface.class);
}
}
public interface myInterface{
    @POST("api/ReadingApi/Something")
    Call<Something> DoReading(
            @Body List<Something> list,
            @Header("Authorization") String auth);

}


Call<DoReadResult> x = RetrofitFactory.getInstance().getlimit().DoReading(
                            data, "Something");

response = x.execute();

更新

implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-jackson:2.5.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'

1 个答案:

答案 0 :(得分:2)

您说过您正在使用翻新,因此您需要使用翻新Call轻松取消通话:

Call<ResponseBody> call =  
    uploadService.uploadSomething(fileUrl);
call.enqueue(new Callback<ResponseBody>() {  
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        Log.d(TAG, "request success");
    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        Log.e(TAG, "request failed");
    }
});
    }

call.cancel();  

with call.cancel();您可以取消您的请求。

在此处查看更多信息:

Retrofit Cancel Request