在 Java 中访问 HTTPS 网站有多种实现方式,下面将详细介绍其中的几种方式,并提供示例代码和相应的依赖坐标。
HttpsURLConnection
是 Java 标准库中用于进行 HTTPS 请求的类。以下是使用这种方式的步骤:
步骤流程:
URL
对象,表示要访问的 HTTPS URL。HttpsURLConnection
连接,通过 url.openConnection()
方法。示例代码:
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class HttpsURLConnectionExample {
public static void main(String[] args) throws IOException {
String urlStr = "https://example.com";
URL url = new URL(urlStr);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
// 设置连接属性
connection.setRequestMethod("GET");
// 获取响应数据
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
}
Maven 依赖:
<dependency>
<groupId>org.codehaus.mojo</groupId>
<artifactId>animal-sniffer-annotations</artifactId>
<version>1.18</version>
</dependency>
Apache HttpClient 是一个广泛使用的 HTTP 客户端库,它可以用于处理 HTTP 和 HTTPS 请求。
步骤流程:
CloseableHttpClient
对象。HttpGet
或 HttpPost
请求对象,设置 URL。示例代码:
import org.apache.http.client.methods.CloseableHttpResponse;
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 ApacheHttpClientExample {
public static void main(String[] args) throws Exception {
String url = "https://example.com";
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpGet = new HttpGet(url);
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println(responseBody);
}
}
}
}
Maven 依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
从 Java 11 开始,引入了一个新的标准库 java.net.http.HttpClient
,用于处理 HTTP 和 HTTPS 请求。
步骤流程:
HttpClient
对象。HttpRequest
对象,设置 URL 和请求方法等。示例代码:
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Java11HttpClientExample {
public static void main(String[] args) throws Exception {
String url = "https://example.com";
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest httpRequest = HttpRequest.newBuilder(new URI(url))
.GET()
.build();
HttpResponse<String> response = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}
无需额外的 Maven 或 Gradle 依赖,因为 Java 11 自带了 java.net.http
包。
请注意,以上示例仅为演示如何在 Java 中访问 HTTPS 网站的几种方式。实际开发中,你可能需要根据具体情况进行更详细的错误处理和配置。