我有一些代码如下:
public class HttpUtil {
public static String sendGetRequest(String url) {
String result = null;
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpGet httpget = new HttpGet(url);
CloseableHttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity);
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
我想知道连接是长连接,因为当我使用sendGetRequest时在HTTP 1.1中使用keepalive。我想在Java中使用长连接。
答案 0 :(得分:0)
默认Connection keep alive strategy可以无限期保持生存状态
如果响应中不存在Keep-Alive标头,则HttpClient会假定连接可以无限期保持活动状态。
要自定义CloseableHttpClient
的保持活动策略,请使用setKeepAliveStrategy
:
CloseableHttpClient client = HttpClients.custom() .setKeepAliveStrategy(myStrategy) .build();