java - OkHttpClient 无法取消通过标签调用

标签 java okhttp

我最近升级到 OkHttp3 ,并注意到您无法再直接从客户端取消通过标签调用。这必须由应用程序现在处理。

CHANGELOG 中说明这里:

Canceling batches of calls is now the application's responsibility. The API to cancel calls by tag has been removed and replaced with a more general mechanism. The dispatcher now exposes all in-flight calls via its runningCalls() and queuedCalls() methods. You can write code that selects calls by tag, host, or whatever, and invokes Call.cancel() on the ones that are no longer necessary.

我正在使用我的简单实用方法自行回答这篇帖子,以通过标签取消正在运行或排队的调用。

最佳答案

使用以下实用程序类通过标记取消正在运行或排队的调用:

public class OkHttpUtils {
    public static void cancelCallWithTag(OkHttpClient client, String tag) {
        // A call may transition from queue -> running. Remove queued Calls first.
        for(Call call : client.dispatcher().queuedCalls()) {
            if(call.request().tag().equals(tag))
                call.cancel();
        }            
        for(Call call : client.dispatcher().runningCalls()) {
            if(call.request().tag().equals(tag))
                call.cancel();
        }
    }
}

我创建了一个示例,这里有一个测试用例:https://gist.github.com/RyanRamchandar/64c5863838940ec67f03

关于java - OkHttpClient 无法取消通过标签调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35964663/

相关文章:

java - 由 : org. apache.maven.plugin.PluginContainerException 引起:

android - SDK < 21 上的改造 2

java.nio.file.Path 无法解析。它是从所需的 .class 文件中间接引用的

java - 从表单后操作中检索值

android - OKHttp Authenticator 不适用于 Retrofit 暂停乐趣

android - okhttp:IllegalArgumentException:意外的 char 0xea

android - 为什么 OkHttp 会默默地替换掉 ws ://or wss://schemes?

java - 关于 Log4jAppender 的问题

java - 要从 OAuth2.0 访问用户电子邮件?

java - Spring Boot在linux中运行Jar文件