0

我正在使用 Apache AsyncHTTPClient 版本 4.1.4(最新)向 API 发送 GET 请求。我似乎无法从服务器获得响应。

这是我的请求日志。

Jun 04, 2020 3:40:01 PM org.apache.http.impl.nio.client.MainClientExec generateRequest
FINE: [exchange: 2] Connection route established
Jun 04, 2020 3:40:01 PM org.apache.http.impl.nio.client.MainClientExec generateRequest
FINE: [exchange: 2] Attempt 1 to execute request
Jun 04, 2020 3:40:01 PM org.apache.http.impl.nio.client.MainClientExec generateRequest
FINE: [exchange: 2] Proxy auth state: UNCHALLENGED
Jun 04, 2020 3:40:01 PM org.apache.http.headers onRequestSubmitted
FINE: http-outgoing-1 >> GET /v1/contact?id=24 HTTP/1.1
Jun 04, 2020 3:40:01 PM org.apache.http.headers onRequestSubmitted
FINE: http-outgoing-1 >> Authorization: Bearer <token_removed>
Jun 04, 2020 3:40:01 PM org.apache.http.headers onRequestSubmitted
FINE: http-outgoing-1 >> Host: api.trial.ezyvet.com
Jun 04, 2020 3:40:01 PM org.apache.http.headers onRequestSubmitted
FINE: http-outgoing-1 >> Connection: Keep-Alive
Jun 04, 2020 3:40:01 PM org.apache.http.headers onRequestSubmitted
FINE: http-outgoing-1 >> User-Agent: Apache-HttpAsyncClient/4.1.4 (Java/11.0.6)
Jun 04, 2020 3:40:01 PM org.apache.http.impl.nio.conn.ManagedNHttpClientConnectionImpl setEvent
FINE: http-outgoing-1 192.168.1.2:52932<->52.27.52.37:443[ACTIVE][rw:][ACTIVE][rw][NEED_UNWRAP][0][0][437]: Event set [w]
Jun 04, 2020 3:40:01 PM org.apache.http.impl.nio.client.MainClientExec requestCompleted
FINE: [exchange: 2] Request completed
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 14.622 s

当我使用 Postman 发送相同的请求时,我得到了成功的响应。

这是我处理连接的代码。

public void connect(HttpUriRequest request, FutureCallback<HttpResponse> callback) {
    SSLContextBuilder sslContextBuilder = new SSLContextBuilder();

    try {
        sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());

        try (CloseableHttpAsyncClient client = HttpAsyncClients.custom()
                .setSSLContext(sslContextBuilder.build())
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .build()) {
            client.start();
            client.execute(request, callback).get();
        }
    } catch (Exception e) {
        Logger.getGlobal().severe("Couldn't execute the request using the AsyncClient.");
    }
}

我的调试器不会在任何回调方法(完成、失败、取消)中被触发。显然连接由于某种原因被终止。

有人可以解释这里发生了什么吗?谢谢

4

1 回答 1

1

I managed to solve this issue by changing the code to include a CountDownLatch instead of using client.execute(request, callback).get().

I passed down the latch to where the HttpResponse is read by JSON deserializer and count it down after everything completes.

This answer helped a lot.

https://stackoverflow.com/a/49359725/6663366

于 2020-06-04T23:10:03.603 回答