JAVA中如何创建异步HTTP请求? [英] How do you create an asynchronous HTTP request in JAVA?
问题描述
我对 Java 还很陌生,所以这对某些人来说似乎很明显.我在 ActionScript 方面做了很多工作,它非常基于事件,我很喜欢它.我最近尝试编写一小段执行 POST 请求的 Java 代码,但我遇到了它是同步请求的问题,因此代码执行等待请求完成、超时或出现错误.
I'm fairly new to Java, so this may seem obvious to some. I've worked a lot with ActionScript, which is very much event based and I love that. I recently tried to write a small bit of Java code that does a POST request, but I've been faced with the problem that it's a synchronous request, so the code execution waits for the request to complete, time out or present an error.
如何创建异步请求,其中代码继续执行并在 HTTP 请求完成时调用回调?我浏览过线程,但我认为这太过分了.
How can I create an asynchronous request, where the code continues the execution and a callback is invoked when the HTTP request is complete? I've glanced at threads, but I'm thinking it's overkill.
推荐答案
注意 java11 现在提供了一个新的 HTTP api HttpClient,支持全异步操作,使用java的CompletableFuture.
Note that java11 now offers a new HTTP api HttpClient, which supports fully asynchronous operation, using java's CompletableFuture.
它还支持同步版本,调用类似 send,同步,sendAsync,这是异步的.
It also supports a synchronous version, with calls like send, which is synchronous, and sendAsync, which is asynchronous.
异步请求示例(取自 apidoc):
Example of an async request (taken from the apidoc):
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com/"))
.timeout(Duration.ofMinutes(2))
.header("Content-Type", "application/json")
.POST(BodyPublishers.ofFile(Paths.get("file.json")))
.build();
client.sendAsync(request, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println);
这篇关于JAVA中如何创建异步HTTP请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!