ava http get请求下载文件_Java Http下载文件到本地 判断是否下载成功
时间: 2023-11-08 16:04:23 浏览: 39
好的,针对您的问题,我可以给您提供以下 Java 代码,用于使用 HTTP GET 请求下载文件并判断是否下载成功:
```java
import java.io.*;
import java.net.*;
public class HttpDownloadUtility {
private static final int BUFFER_SIZE = 4096;
/**
* 用 HTTP GET 请求下载文件到本地
* @param fileURL 文件的URL地址
* @param saveDir 文件保存的目录
* @return 文件保存的绝对路径,如果下载失败则返回 null
* @throws IOException
*/
public static String downloadFile(String fileURL, String saveDir)
throws IOException {
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// 如果HTTP响应码是200,表示连接成功
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// 从Content-Disposition中获取文件名
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// 从URL中获取文件名
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// 打开网络输入流
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
// 打开本地文件输出流
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
// 读取网络输入流到本地文件输出流
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("文件下载成功");
return saveFilePath;
} else {
System.out.println("文件下载失败,响应码是 " + responseCode);
return null;
}
}
}
```
使用方法:
```java
public static void main(String[] args) {
String fileURL = "http://example.com/file.zip";
String saveDir = "C:/downloads";
try {
HttpDownloadUtility.downloadFile(fileURL, saveDir);
} catch (IOException ex) {
ex.printStackTrace();
}
}
```
以上代码将会把 `http://example.com/file.zip` 下载到本地的 `C:/downloads` 目录下。
希望能对您有所帮助!