【问题标题】:Okhttp : Asynchronous request doesn't stop immediately after onResponseOkhttp:异步请求不会在 onResponse 之后立即停止
【发布时间】:2021-04-07 22:26:18
【问题描述】:

首先对不起我的英语不是我的母语。

我使用 okhttp 进行一些简单的异步调用,但我的程序在调用 onResponse 后并没有立即停止。它需要几秒钟然后停止。我在 Android 5 上没有这个问题,但在我的桌面上。我对其他 URL 也有同样的问题。也许我做错了什么。该请求在另一个线程中执行。我的网络在代理下。

我使用:okhttp-2.4.0okio-1.4.0java8

如果此问题已得到解答,请重定向我。

这是我的代码:`

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {

    Settings.setProxy();
    Request request = new Request.Builder()
            .url("http://openlibrary.org/search.json?q=la+famille")
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            e.printStackTrace();
            System.out.println("error");
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            System.out.println(response.body().string());
            System.out.println("coucou");
        }
    });
}

`

【问题讨论】:

标签: java okhttp


【解决方案1】:

当您执行异步调用时,您会从该问题中发现 ExecutorService 已创建并且池使 VM 保持活动状态。

要关闭池,只需获取调度程序并关闭它:

client.getDispatcher().getExecutorService().shutdown();

【讨论】:

  • 你能解释一下为什么它没有自动关闭,之前用 OkHttp 可以正常工作,现在不行,有什么具体原因吗?
  • 对于较新的版本,上面的代码应该是:client.dispatcher().executorService().shutdown();
【解决方案2】:

我不知道如何,但这条线对我有用 client.connectionPool().evictAll();

【讨论】:

    猜你喜欢
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    • 2012-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多