下面是一个使用Apache HttpUtils下载文件的示例代码:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class FileDownloader {
public static void main(String[] args) {
String fileUrl = "http://example.com/file.txt";
String savePath = "C:/path/to/save/file.txt";
try {
downloadFile(fileUrl, savePath);
System.out.println("File downloaded successfully.");
} catch (IOException e) {
System.out.println("Failed to download file: " + e.getMessage());
}
}
public static void downloadFile(String fileUrl, String savePath) throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(fileUrl);
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
try (InputStream inputStream = entity.getContent();
OutputStream outputStream = new FileOutputStream(savePath)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
} finally {
EntityUtils.consume(entity);
}
}
}
}
以上示例代码使用Apache HttpUtils库下载文件。首先,创建一个CloseableHttpClient实例。然后,创建HttpGet对象,设置文件的URL。接下来,执行HttpGet请求并获取HttpResponse对象。通过HttpResponse对象可以获取文件的HttpEntity。如果HttpEntity不为null,我们可以使用输入流从HttpEntity中读取文件内容,并将其写入输出流中。最后,我们关闭输入流、输出流和HttpEntity。
在main方法中,我们可以指定文件的URL和保存路径,然后调用downloadFile方法来下载文件。如果下载成功,将打印"File downloaded successfully.";如果下载失败,将打印"Failed to download file: ..."并输出错误信息。