我正在使用 Spring RestTemplate,并且想要调用另一个不返回任何响应正文的服务。所以,我不想等待回复。因此,只需即发即忘,然后继续剩余的代码。我正在考虑创建一个新线程来执行此操作,但不确定什么是正确的方法。
如果您使用Java 11,java支持异步HTTP Client。异步客户端使用完整的未来 https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html在后面。你可以看到javadoc https://openjdk.java.net/groups/net/httpclient/intro.html.
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://openjdk.java.net/"))
.timeout(Duration.ofMinutes(1))
.header("Content-Type", "application/json")
.POST(BodyPublishers.ofFile(Paths.get("file.json")))
.build();
client.sendAsync(request, BodyHandlers.ofString())
.thenApply(response -> { System.out.println(response.statusCode());
return response; } )
.thenApply(HttpResponse::body)
.thenAccept(System.out::println);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)