我发现此代码在独立的 Java 应用程序(可运行的 JAR)上运行,而在 Tomcat (8) 上的 WAR 中部署时速度极慢,我找不到原因。可运行的 JAR 使用与 WAR 相同的 Apache Http 客户端库和相同的 Java 版本 (8)。 我注意到服务器不返回“内容长度”响应头并使用“分块编码”功能。 我启用了 http 线路日志记录,我发现在“tomcat”情况下,响应正文(响应总大小约为 2MB)到达但速度非常慢(超过 4 分钟),而在独立情况下,所有响应都在几秒钟内到达.
public static void main(String[] args) throws Exception {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(3000)
.setConnectionRequestTimeout(3000)
.setSocketTimeout(10000)
.build();
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy).build();
CloseableHttpClient httpClient = HttpClients.custom().setSSLContext(sslContext)
.setSSLHostnameVerifier(getHostnameVerifier()).setDefaultRequestConfig(requestConfig).build();
try {
HttpGet req = new HttpGet("https://someurl");
((HttpGet) req).setHeader("Accept", "*/*");
((HttpGet) req).setHeader("Content-Type", "application/json");
HttpResponse httpResponse = httpClient.execute(req);
if ((httpResponse != null) && (httpResponse.getStatusLine() != null)
&& (httpResponse.getStatusLine().getStatusCode() == 200)) {
System.out.println(EntityUtils.toString(httpResponse.getEntity()));
}
} catch (Exception e) {
System.out.println("Exception" + e);
}
}
更新:使用另一个 http 客户端 (okhttp) 我遇到了同样的“问题”,在 Tomcat 上我在 4 分钟后得到了响应;现在我认为这是与 Tomcat 相关的东西......疯狂。
OkHttpClient client = getUnsafeOkHttpClient();
Request request = new Request.Builder().url("https://someurl").build();
String body = null;
logger.info("HTTP REQUEST BEGIN");
try (Response response = client.newCall(request).execute()) {
logger.info("HTTP REQUEST END");
body = response.body().string(); // here waits a lot...
} catch (Exception e) {
logger.info("exception=" + e);
}
logger.info("response=" + body);