java—可以使用okhttp的排队方法返回响应吗?

wztqucjr  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(321)

我现在用的是普通的 newCall(Request).execute() 正如在okio的一个例子中所解释的,但我更愿意使用 enqueue 方法执行的操作必须是异步的。
然而,我面临的问题是,我必须返回一个字符串,该字符串是由请求的响应生成的。
在这种情况下 execute 方法现在看起来是这样的:

public class HttpUtil{
    private final OkHttpClient CLIENT = new OkHttpClient();

    public HttpUtil(){}

    public String getImage(String url) throws IOException{
        Request request = new Request.Builder()
                .url(url)
                .build();

        try(Response response = CLIENT.newCall(request).execute()){
            if(!response.isSuccessful())
                throw new IOException(String.format(
                        "Unexpected code from url %s: %s",
                        url,
                        response
                ));

            ResponseBody body = response.body();
            if(body == null)
                throw new NullPointerException("Received empty body!");

            String bodyString = body.string();
            if(bodyString.isEmpty())
                throw new NullPointerException("Received empty body!");

            return new JSONObject(bodyString).getString("link");
        }
    }
}

从上面的方法可以看出,我使用返回的body作为string生成了一个新的jsonobject,然后得到“link”的字段值。
在使用enqueue方法时,是否还有任何方法可以返回字符串?

7d7tgy0s

7d7tgy0s1#

返回一个future,这样您就可以实际地进行异步编程,否则,在尝试保持简单的同步方法的同时,使用异步方法使代码复杂化是一个毫无意义的练习。

public class HttpUtil {
  private final OkHttpClient CLIENT = new OkHttpClient();

  public Future<String> getImage(String url) throws IOException {
    Request request = new Request.Builder()
      .url(url)
      .build();

    CompletableFuture<String> f = new CompletableFuture<>();

    CLIENT.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(@NotNull Call call, @NotNull IOException e) {
          f.completeExceptionally(e);
        }

        @Override
        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
          if (!response.isSuccessful())
            throw new IOException(String.format(
              "Unexpected code from url %s: %s",
              url,
              response
            ));

          String bodyString = response.body().string();

          f.complete(new JSONObject(bodyString).getString("link"));
        }
      }
    );

    return f;
  }
}

相关问题