OkHttp通常是异步的。常规调用如下所示:
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
}
}
}当消息到达时,只需对其做点什么。但是我想把它当做一个阻塞的getter。类似于:
public void exampleMethod() {
MyDTO myDto = makeOkHttpCall.getData();
// do something with myDto Entity
}但是我所能找到的就是我可以在onResponse()中添加代码。但这仍然是异步的。有什么想法可以改变这一点吗?
发布于 2020-05-15 19:10:07
您可以使用execute来同步执行请求,而不是使用enqueue。
请参阅OkHttp文档中的示例:
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文档:https://square.github.io/okhttp)
https://stackoverflow.com/questions/61817617
复制相似问题