Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make OkHttp calls synchronous/blocking?

Tags:

java

okhttp

OkHttp is usually asynchronous. A regular call looks like this:

client.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        e.printStackTrace();
    }

    @Override
    public void onResponse(Call call, final Response response) throws IOException {
        if (!response.isSuccessful()) {
            throw new IOException("Unexpected code " + response);
        } else {
            // do something wih the result
        }
    }
}

When the message arrives, just do something with it. But I want to use it as a blocking getter. Something like:

public void exampleMethod() {
   MyDTO myDto = makeOkHttpCall.getData();
   // do something with myDto Entity
}

But all I can find is that I could add code into onResponse(). But that is still asynchronous. Any ideas how to change that?

like image 620
TheAmygdala Avatar asked Oct 29 '25 09:10

TheAmygdala


1 Answers

Instead of enqueue you can use execute to execute a request synchronously.

See example from the OkHttp documentation:

OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
    Request request = new Request.Builder()
            .url(url)
            .build();

    try (Response response = client.newCall(request).execute()) {
        return response.body().string();
    }
}

(OkHttp documentation: https://square.github.io/okhttp)

like image 119
Matt Ke Avatar answered Oct 31 '25 22:10

Matt Ke