java 实现https下载文件
时间: 2023-12-21 09:31:04 浏览: 49
以下是使用Java实现HTTPS下载文件的示例代码:
```java
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class HttpsDownloader {
public static void main(String[] args) {
String fileUrl = "https://example.com/file.txt";
String savePath = "C:/path/to/save/file.txt";
try {
URL url = new URL(fileUrl);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
FileOutputStream fileOutputStream = new FileOutputStream(savePath);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
fileOutputStream.close();
bufferedInputStream.close();
System.out.println("File downloaded successfully.");
} else {
System.out.println("Failed to download file. Response code: " + responseCode);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
请注意,为了实现HTTPS下载文件,你需要引入`httpclient-4.5.13.jar`和`httpcore-4.4.14.jar`这两个包。这些包提供了Java中处理HTTP和HTTPS请求的功能。