使用HttpAsyncClient发送异步调用时出现问题

问题描述 投票:0回答:1

我想在java中向servlet发送异步post请求。我正在使用apache HttpAsyncClient,如下面的方法所示。当我调试时,我看到调用此方法的进程等待,直到被调用的servlet完成其处理。换句话说,调用似乎是同步的而不是异步的。你知道我做错了什么部分吗?

谢谢!

public void sendPostRequestUsingHttpAsyncClient( String params)  {

    try (CloseableHttpAsyncClient client = HttpAsyncClients.createDefault()) {
        client.start();
        HttpPost request = new HttpPost(URL);
        StringEntity entity = new StringEntity(params, ContentType.create("application/json", Consts.UTF_8));
        request.setEntity(entity);
        Future<HttpResponse> future = client.execute(request, null);
        try {
            System.out.println(future.get().getStatusLine().getStatusCode());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}
java asynchronous apache-httpclient-4.x
1个回答
1
投票

在执行future.get()时,您的代码将被阻止,直到成功执行HTTP请求

您似乎对异步的期望与代码中的实际情况有点远。要获得HttpAsyncClient的好处,您可以在开始时执行多个请求,然后使用某个同步原语等待所有请求完成。

© www.soinside.com 2019 - 2024. All rights reserved.