Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Okhttp : Asynchronous request doesn't stop immediately after onResponse

Tags:

java

okhttp

First sorry for my English which is not my native language.

I use okhttp to do some simple asynchronous calls but my program doesn't stop immediately after the call of onResponse. It takes some seconds and then stops. I don't have this issue on Android 5 but on my desktop. I have the same issue with others URLs. Maybe there is something I did wrong. The request is performed in another thread. My network is under a proxy.

I use : okhttp-2.4.0 and okio-1.4.0 and java8.

Redirect me if this issue was already answered.

This my code : `

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

`

like image 899
Mohamed El Mouctar HAIDARA Avatar asked Jul 02 '15 11:07

Mohamed El Mouctar HAIDARA


People also ask

Is OkHttp asynchronous?

OkHttp doesn't currently offer asynchronous APIs to receive a response body in parts.

How does OkHttp work?

OkHttp is an efficient HTTP & HTTP/2 client for Android and Java applications. It comes with advanced features, such as connection pooling (if HTTP/2 isn't available), transparent GZIP compression, and response caching, to avoid the network completely for repeated requests.

How do you use OkHttp in Kotlin?

To get include the latest version of OkHttp in your app's gradle file. Sync the project to download the library. Once that is done, I developed a Kotlin class file, called OkHttpRequest. This class is used to make requests and to parse response.

What is OkHttp library in Android?

OkHttp is a third-party library developed by Square for sending and receive HTTP-based network requests. It is built on top of the Okio library, which tries to be more efficient about reading and writing data than the standard Java I/O libraries by creating a shared memory pool.


1 Answers

As you find out from the issue when you do an async call an ExecutorService is created and the pool is keeping the VM alive.

To shutdown the pool just get the dispatcher and close it:

client.getDispatcher().getExecutorService().shutdown();
like image 143
Enrichman Avatar answered Sep 19 '22 02:09

Enrichman