java – Okhttp:onResponse后异步请求不会立即停止

首先抱歉我的英语不是我的母语.

我使用okhttp做一些简单的异步调用,但我的程序在调用onResponse后不会立即停止.它需要几秒钟然后停止.我在Android 5上没有这个问题,但在我的桌面上.我对其他网址也有同样的问题.也许有些事我做错了.请求在另一个线程中执行.我的网络是代理服务器.

我使用:okhttp-2.4.0和okio-1.4.0和java8.

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

我的代码:`

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");
        }
    });
}

`

最佳答案 正如您在执行异步调用时从问题中发现的那样,创建了ExecutorService并且池正在使VM保持活动状态.

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

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