我对 Java 相当陌生,所以这对某些人来说可能是显而易见的。我经常使用 ActionScript,它非常基于事件,我喜欢它。我最近尝试编写一小段执行 POST 请求的 Java 代码,但我遇到了一个问题:它是同步请求,因此代码执行会等待请求完成、超时或出现错误。
如何创建异步请求,其中代码继续执行并在 HTTP 请求完成时调用回调?我浏览过线程,但我认为这有点过分了。
最佳答案
如果您处于 JEE7 环境中,则必须有一个不错的 JAXRS 实现,这将允许您使用其客户端 API 轻松发出异步 HTTP 请求。
这看起来像这样:
public class Main {
public static Future<Response> getAsyncHttp(final String url) {
return ClientBuilder.newClient().target(url).request().async().get();
}
public static void main(String ...args) throws InterruptedException, ExecutionException {
Future<Response> response = getAsyncHttp("http://www.nofrag.com");
while (!response.isDone()) {
System.out.println("Still waiting...");
Thread.sleep(10);
}
System.out.println(response.get().readEntity(String.class));
}
}
当然,这只是使用 future。如果您可以使用更多库,您可以看看 RxJava,代码将如下所示:
public static void main(String... args) {
final String url = "http://www.nofrag.com";
rx.Observable.from(ClientBuilder.newClient().target(url).request().async().get(String.class), Schedulers
.newThread())
.subscribe(
next -> System.out.println(next),
error -> System.err.println(error),
() -> System.out.println("Stream ended.")
);
System.out.println("Async proof");
}
最后但并非最不重要的一点是,如果您想重用异步调用,您可能需要看看 Hystrix,它 - 除了无数超酷的其他东西之外 - 还允许您编写如下内容:
例如:
public class AsyncGetCommand extends HystrixCommand<String> {
private final String url;
public AsyncGetCommand(final String url) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("HTTP"))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
.withExecutionIsolationThreadTimeoutInMilliseconds(5000)));
this.url = url;
}
@Override
protected String run() throws Exception {
return ClientBuilder.newClient().target(url).request().get(String.class);
}
}
调用此命令如下所示:
public static void main(String ...args) {
new AsyncGetCommand("http://www.nofrag.com").observe().subscribe(
next -> System.out.println(next),
error -> System.err.println(error),
() -> System.out.println("Stream ended.")
);
System.out.println("Async proof");
}
PS:我知道该线程很旧,但没有人在投票的答案中提到 Rx/Hystrix 方式,这感觉不对。
关于java - 如何在 JAVA 中创建异步 HTTP 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59482258/