java如何连接网址
使用 HttpURLConnection 连接网址
HttpURLConnection 是 Java 标准库中用于 HTTP 请求的类,适合简单的请求场景。
创建 URL 对象并打开连接:
URL url = new URL("https://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
设置请求方法(默认为 GET):
connection.setRequestMethod("GET");
读取响应内容:
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
关闭连接:
connection.disconnect();
使用 HttpClient 连接网址(Java 11+)
HttpClient 是 Java 11 引入的现代 HTTP 客户端 API,功能更强大。
创建 HttpClient 实例:
HttpClient client = HttpClient.newHttpClient();
构建请求:
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com"))
.build();
发送请求并处理响应:
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
String body = response.body();
使用第三方库(Apache HttpClient)
对于更复杂的需求,可以使用 Apache HttpClient 库。
添加 Maven 依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
创建 CloseableHttpClient 实例:
CloseableHttpClient httpClient = HttpClients.createDefault();
执行 GET 请求:
HttpGet httpGet = new HttpGet("https://example.com");
CloseableHttpResponse response = httpClient.execute(httpGet);
读取响应内容:
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
关闭资源:
response.close();
httpClient.close();
处理 HTTPS 连接
对于 HTTPS 网址,可能需要配置 SSL 上下文:
创建信任所有证书的 SSL 上下文(仅限测试环境):
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[]{new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) {}
public void checkServerTrusted(X509Certificate[] chain, String authType) {}
public X509Certificate[] getAcceptedIssuers() { return null; }
}}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
处理连接超时
设置连接和读取超时(单位毫秒):
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
对于 HttpClient:

HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();






