java使用post请求下载文件
时间: 2023-10-16 07:10:27 浏览: 160
在Java中,可以使用HttpURLConnection或Apache HttpClient来执行POST请求并下载文件。以下是使用HttpURLConnection的示例代码:
```java
import java.io.*;
import java.net.*;
public class DownloadFile {
public static void main(String[] args) {
String url = "http://example.com/download/file";
String filePath = "C:/downloads/file.txt";
try {
URL downloadUrl = new URL(url);
HttpURLConnection httpConn = (HttpURLConnection) downloadUrl.openConnection();
httpConn.setDoOutput(true);
httpConn.setRequestMethod("POST");
OutputStream outputStream = httpConn.getOutputStream();
outputStream.write("param1=value1¶m2=value2".getBytes());
outputStream.flush();
outputStream.close();
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpConn.getInputStream();
FileOutputStream outputStream = new FileOutputStream(filePath);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded successfully.");
} else {
System.out.println("Server returned response code: " + responseCode);
}
httpConn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们首先创建一个URL对象,然后使用HttpURLConnection打开连接。设置doOutput为true以启用输出流,并将请求方法设置为POST。接下来,我们将POST参数写入输出流中。然后,我们获取服务器响应代码,并检查是否为HTTP_OK(200)。如果是,我们将响应流复制到文件输出流中,从而将文件写入本地磁盘。最后,我们关闭所有流并断开连接。
阅读全文