用java实现application/octet-stream请求,方式为POST,文件流是 easyexcel动态写入,请求头中有filename参数支持中文
时间: 2023-06-06 22:09:05 浏览: 438
可以使用Java中的HttpURLConnection类进行POST请求,并设置请求头中的filename参数。示例代码如下:
```java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class PostOctetStreamRequest {
public static void main(String[] args) throws Exception {
String urlStr = "http://example.com/upload";
String fileName = "测试文件.xlsx"; // 中文文件名
String boundary = "Boundary" + System.currentTimeMillis(); // 分隔符
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
OutputStream outputStream = conn.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true);
// 添加文件流
writer.println("--" + boundary);
writer.println("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"");
writer.println("Content-Type: application/octet-stream");
writer.println();
EasyExcel.write(outputStream, Object.class).sheet().doWrite(dataList); // EasyExcel动态写入文件流
writer.println();
writer.flush();
// 添加分隔符和结束符
writer.println("--" + boundary + "--");
writer.close();
// 获取响应结果
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
StringBuilder result = new StringBuilder();
while ((line = reader.readLine()) != null) {
result.append(line);
}
reader.close();
System.out.println(result.toString());
}
}
```
通过这样的方式,你可以使用Java语言实现application/octet-stream请求,实现动态写入文件流并携带请求头参数,支持中文文件名。
阅读全文