java中用post方式访问第三方接口返回一个文件如何接收保存到本地
在Java中,可以使用HttpURLConnection类来发送POST请求,并接收和保存返回的文件。
以下是一个示例代码:
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) {
String urlStr = "http://example.com/api"; // 第三方接口的URL
String filePath = "/path/to/save/file.txt"; // 保存文件的本地路径
try {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true); // 允许发送数据
conn.setDoInput(true); // 允许接收数据
// 设置请求头
conn.setRequestProperty("Content-Type", "application/json");
// 设置请求体
String requestBody = "{\"key\":\"value\"}";
OutputStream os = conn.getOutputStream();
os.write(requestBody.getBytes());
os.flush();
os.close();
// 获取返回的文件
InputStream is = conn.getInputStream();
FileOutputStream fos = new FileOutputStream(new File(filePath));
int bytesRead;
byte[] buffer = new byte[4096];
while ((bytesRead = is.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
fos.close();
is.close();
System.out.println("文件保存成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
在以上代码中,我们首先创建一个URL对象,并使用HttpURLConnection打开连接。然后,我们设置请求方法为POST,并设置请求头和请求体。
接下来,我们使用getInputStream()方法获取返回的文件流,然后将其写入到本地文件中。在写入文件时,我们使用一个缓冲区来提高效率。
最后,我们关闭文件输出流和文件输入流,并打印保存成功的消息。
请注意,在实际使用中,你需要将示例代码中的URL、请求头、请求体和保存文件路径等根据实际情况进行修改
原文地址: http://www.cveoy.top/t/topic/iTle 著作权归作者所有。请勿转载和采集!