首页 > 解决方案 > 无法停止改装发送

问题描述

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

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

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

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

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

我的代码:

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'

标签: javaandroidsocketsretrofit2okhttp3

解决方案


正如您所说,您正在使用 retrofit ,因此您需要使用 retrofit 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();  

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

在这里查看更多:

改造取消请求


推荐阅读