如何使 OkHttp 调用同步/阻塞?

The*_*ala 3 java okhttp

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当消息到达时,只需对其执行一些操作即可。但我想用它作为阻塞吸气剂。就像是:

public void exampleMethod() {
   MyDTO myDto = makeOkHttpCall.getData();
   // do something with myDto Entity
}
Run Code Online (Sandbox Code Playgroud)

但我能找到的只是我可以将代码添加到onResponse(). 但这仍然是异步的。有什么想法如何改变这一点吗?

Mat*_* Ke 6

相反,enqueue您可以使用execute同步执行请求。

请参阅 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

(OkHttp 文档: https: //square.github.io/okhttp