Java-从OkHttp异步GET检索结果 [英] Java - Retrieving Result from OkHttp Asynchronous GET

查看:448
本文介绍了Java-从OkHttp异步GET检索结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我在Spring Boot中有一个Web应用程序,在某个部分中,我向API发出了许多HTTP请求,并且如果发出过多的请求,似乎会超时.我听说从同步"请求转换为异步"请求可能会解决此问题.

So I have a web-app in Spring Boot, and there is a part where I make many HTTP requests to an API, and it seems to timeout if too many requests are made. I heard that switching from Synchronous to Asynchronous requests might help this issue.

使用OkHttp,这是我的同步GET请求的样子:

Using OkHttp, this is what my Synchronous GET request looks like:

private JSONObject run(String url) throws Exception {
    Request newRequest = new Request.Builder()
            .url(url)
            .addHeader("Authorization", token)
            .build();

    try (Response response = client.newCall(newRequest).execute()) {
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
        return new JSONObject(response.body().string());

    }
}

我通过解析响应主体将响应作为JSON对象返回.但是,在尝试使用OkHttp异步调用时,似乎无法使用相同的方法.这是我到目前为止所拥有的:

I return the response as a JSON object from parsing the response body. However, in trying to use an OkHttp asynchronous call, it seems that I can't use the same approach. This is what I have so far:

public void runAsync(String url) throws Exception {
    Request request = new Request.Builder()
            .url(url)
            .addHeader("Authorization", token)
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }

        @Override public void onResponse(Call call, Response response) throws IOException {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            System.out.println(response.body().string());
        }
    });
}

我不能简单地以JSON形式返回结果,因为响应被包装在Callback方法内部,该方法的返回值为void.关于如何获得与提取响应的同步GET类似的结果的任何想法?

I cannot simply return the result as a JSON, as the response is wrapped inside of the Callback method, which has a return value of void. Any ideas on how I might achieve similar results to my Synchronous GET of extracting the response?

推荐答案

我不是Spring Boot的用户,所以这不是一个完整的答案.但是,如果它支持返回Future,那么从OkHttp Callback到Future桥接是很简单的.

I'm not a user of Spring Boot, so this is not a complete answer. But if it supports returning a Future, then it's trivial to bridge from OkHttp Callback to a Future.

这可能与 https://spring.io/guides/gs/async-方法/

关于创造未来

public class OkHttpResponseFuture implements Callback {
  public final CompletableFuture<Response> future = new CompletableFuture<>();

  public OkHttpResponseFuture() {
  }

  @Override public void onFailure(Call call, IOException e) {
    future.completeExceptionally(e);
  }

  @Override public void onResponse(Call call, Response response) throws IOException {
    future.complete(response);
  }
}

然后将工作入队

  OkHttpResponseFuture callback = new OkHttpResponseFuture();
  client.newCall(request).enqueue(callback);

  return callback.future.thenApply(response -> {
    try {
      return convertResponse(response);
    } catch (IOException e) {
      throw Throwables.propagate(e);
    } finally {
      response.close();
    }
  });

如果您有多个请求要处理,则可以分别提交它们,然后等待所有结果可用,然后再组合并返回

If you have multiple requests to process you can submit them separately and then wait on all results being available before combining and returning

  public static <T> CompletableFuture<List<T>> join(List<CompletableFuture<T>> futures) {
    CompletableFuture[] cfs = futures.toArray(new CompletableFuture[futures.size()]);

    return CompletableFuture.allOf(cfs)
        .thenApply(v -> combineIndividualResults(c));
  }

这篇关于Java-从OkHttp异步GET检索结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆