0

我正在构建一个使用 Web 服务的客户端。我需要做的一件事是发送一个 POST 请求,然后存储返回的 cookie。当我使用 curl 命令发送它时,得到响应大约需要不到 2 秒的时间。这是我使用的命令:

curl -c cookies.txt --cert client_certificate -X POST -H "Content-Type: application/json" -d 'request_body' "https://my_target_web_service"

但是,当我使用 Apache httpclient (4.3.1) 时,大约需要 5 秒。以下是方法:

@Test
public void firstCall() throws Exception {
    final String url = "https://my_target_web_service";
    final String requestBody = readFile("json/request_body.json");
    Executor executor = executor();
    CookieStore cookieStore = new BasicCookieStore();
    executor.cookieStore(cookieStore);

    Request request = Request.Post(url).bodyString(requestBody, ContentType.APPLICATION_JSON);
    LOG.debug(request.toString());

    Response response = executor.execute(request);
    LOG.info(response.returnResponse().getStatusLine().toString());
}

private Executor executor() throws Exception {
    KeyStore clientStore = secretKeyStore();
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(clientStore, "secret_key".toCharArray()).useTLS().build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
            SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    Executor executor = Executor.newInstance(httpclient);
    return executor;
}

LOG 输出显示大部分时间都花在建立与 Web 服务的连接上(注意从 15:44:12,610 跳转到 15:44:17,426):

DEBUG [2013-10-16 15:44:12,485] [main                          ] org.apache.http.client.protocol.RequestAddCookies: CookieSpec selected: best-match
DEBUG [2013-10-16 15:44:12,500] [main                          ] org.apache.http.impl.conn.PoolingHttpClientConnectionManager: Connection request: [route: {s}->https://...:443][total kept alive: 0; route allocated: 0 of 2; total allocated: 0 of 20]
DEBUG [2013-10-16 15:44:12,517] [main                          ] org.apache.http.impl.conn.PoolingHttpClientConnectionManager: Connection leased: [id: 0][route: {s}->https://...:443][total kept alive: 0; route allocated: 1 of 2; total allocated: 1 of 20]
DEBUG [2013-10-16 15:44:12,524] [main                          ] org.apache.http.impl.execchain.MainClientExec: Opening connection {s}->https://...:443
DEBUG [2013-10-16 15:44:12,610] [main                          ] org.apache.http.conn.HttpClientConnectionManager: Connecting to ...:443
DEBUG [2013-10-16 15:44:17,426] [main                          ] org.apache.http.impl.execchain.MainClientExec: Executing request POST / HTTP/1.1
DEBUG [2013-10-16 15:44:17,427] [main                          ] org.apache.http.impl.execchain.MainClientExec: Target auth state: UNCHALLENGED
DEBUG [2013-10-16 15:44:17,427] [main                          ] org.apache.http.impl.execchain.MainClientExec: Proxy auth state: UNCHALLENGED

谁能告诉我我错过了什么或做错了什么?或者,这是 httpclient 和/或 java 的限制吗?

谢谢,

4

0 回答 0