java如何请求长链接
使用 Java 请求长链接(HTTP Keep-Alive)
在 Java 中实现长链接(HTTP Keep-Alive)可以通过以下方法完成,主要利用 HttpURLConnection 或第三方库如 Apache HttpClient。
使用 HttpURLConnection 实现
默认情况下,HTTP/1.1 支持 Keep-Alive,但需要正确设置连接参数。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class KeepAliveExample {
public static void main(String[] args) throws Exception {
URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 启用 Keep-Alive
connection.setRequestProperty("Connection", "Keep-Alive");
// 设置超时时间(可选)
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
// 发送请求
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 读取响应
try (BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()))) {
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
System.out.println(response.toString());
}
// 不关闭连接以便复用
// connection.disconnect();
}
}
使用 Apache HttpClient 实现
Apache HttpClient 提供了更高级的 Keep-Alive 支持。
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientKeepAlive {
public static void main(String[] args) throws Exception {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet request = new HttpGet("http://example.com");
// 发送请求
HttpResponse response = httpClient.execute(request);
System.out.println("Status Code: " + response.getStatusLine().getStatusCode());
// 读取响应
String result = EntityUtils.toString(response.getEntity());
System.out.println(result);
}
}
}
配置连接池(高级)
对于高频请求,可以使用连接池优化性能。

import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public class ConnectionPoolExample {
public static void main(String[] args) {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(100); // 最大连接数
cm.setDefaultMaxPerRoute(20); // 每个路由的最大连接数
try (CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(cm)
.build()) {
// 使用 httpClient 发送请求
}
}
}
注意事项
- Keep-Alive 依赖于服务器支持,需确保服务器端未关闭连接。
- 长时间空闲的连接可能被服务器或防火墙终止,需处理异常。
- 使用连接池时注意资源释放,避免内存泄漏。
通过以上方法,可以在 Java 中高效地实现长链接请求。






