java post请求调用文件下载接口并保存文件到本地
时间: 2024-09-18 18:12:13 浏览: 41
JAVA发送http get/post请求,调用http接口、方法详解
5星 · 资源好评率100%
在Java中,你可以使用`java.net.URLConnection`或者第三方库如`Apache HttpClient`或`OkHttp`来发送POST请求并下载文件。以下是一个基本示例,使用`URLConnection`:
```java
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileDownloadExample {
public static void main(String[] args) {
String downloadUrl = "http://example.com/file-to-download"; // 替换为你实际的文件下载地址
String saveFilePath = "/path/to/save/downloaded/file"; // 替换为你想要保存的位置
try {
URL url = new URL(downloadUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST"); // 设置请求方法为POST,如果需要可以添加其他请求头
// 如果有post数据,设置连接的Content-Type和POST数据
if (!connection.getRequestProperty("Content-Type").isEmpty()) {
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
}
connection.connect(); // 连接服务器
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // 检查HTTP状态码是否为200
InputStream inputStream = connection.getInputStream();
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
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("File downloaded successfully.");
} else {
System.err.println("Failed to download file. Server responded with code: " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
阅读全文