java post下载文件
时间: 2024-11-24 14:14:29 浏览: 4
VUE + java 文件下载
5星 · 资源好评率100%
在Java中,你可以使用HttpURLConnection或者第三方库如Apache HttpClient或者OkHttp来进行POST请求并下载文件。这里是一个基本的例子,使用HttpURLConnection:
```java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadFile {
public static void main(String[] args) throws IOException {
String url = "http://example.com/file-to-download.zip"; // 替换为你需要下载的文件URL
try (BufferedInputStream in = new BufferedInputStream(
new URL(url).openStream())) {
File file = new File("downloaded-file.zip"); // 文件保存路径
FileOutputStream out = new FileOutputStream(file);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
out.close();
in.close();
System.out.println("Download complete.");
} catch (IOException e) {
System.err.println("Error occurred during download: " + e.getMessage());
}
}
}
```
这个例子首先创建一个URL对象,并通过`openStream()`方法获取到连接到服务器的输入流。然后,将输入流读取的数据写入本地文件中。最后关闭流以释放资源。
阅读全文