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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With