我正在构建一个使用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输出显示大部分时间花在建立与webservice的连接上(请注意从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的限制吗?
谢谢,