java 文件下载添加header属性Content-Length
时间: 2024-10-09 10:11:55 浏览: 54
在Java中下载文件并添加HTTP header属性`Content-Length`通常涉及到使用HttpURLConnection、HttpClient或者其他支持HTTP请求的库。这里是一个基本的例子,使用`HttpURLConnection`:
```java
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public void downloadFileWithLength(String urlString, String destinationPath) throws Exception {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 添加Content-Length头信息
long fileSize = getFileSize(url); // 获取文件大小
connection.setRequestProperty("Content-Length", Long.toString(fileSize));
// 设置GET请求
connection.setRequestMethod("GET");
// 打开连接并获取响应码
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
// 创建目标文件并写入数据
OutputStream outputStream = new FileOutputStream(destinationPath);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("Downloaded file to " + destinationPath);
} else {
throw new RuntimeException("Failed to download file with status code: " + responseCode);
}
connection.disconnect();
}
private long getFileSize(URL url) throws Exception {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("HEAD"); // 使用HEAD请求只获取头部信息,不会下载文件内容
long fileSize = connection.getContentLengthLong(); // 获取头信息中的Content-Length字段
connection.disconnect();
return fileSize;
}
```
在这个例子中,首先我们打开一个到URL的连接,并设置`Content-Length`头,然后发送一个GET请求来下载文件。如果服务器返回状态码为200(表示成功),我们就读取输入流并将其写入到指定的本地文件。
阅读全文