【问题标题】:How can I make OkHttp calls synchronous/blocking?如何使 OkHttp 调用同步/阻塞?
【发布时间】:2020-09-01 04:24:15
【问题描述】:

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
        }
    }
}

当消息到达时,只需对它做一些事情。但我想用它作为阻塞吸气剂。比如:

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

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

【问题讨论】:

    标签: java spring-boot okhttp


    【解决方案1】:

    您可以使用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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-06
      • 2013-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      相关资源
      最近更新 更多