簡體   English   中英

無法停止更新發送

[英]Can not stop retrofit sending

我使用改造和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'

如您所說,您正在使用改造,因此您需要使用改造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(); 您可以取消您的請求。

在這里查看更多:

改裝取消請求

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM