Reputation: 75
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?
Upvotes: 4
Views: 3829
Reputation: 4375
Just look at the OkHttp recipes on their website.
You will find for example :
The example for Synchronous Get in Java being :
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("https://publicobject.com/helloworld.txt")
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
for (int i = 0; i < responseHeaders.size(); i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(response.body().string());
}
}
Upvotes: 1
Reputation: 3739
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)
Upvotes: 8