java编写Multipartfile/from-data的http请求
时间: 2024-09-12 15:13:00 浏览: 40
在Java中,当你需要发送一个多部分文件(Multipart/form-data)的HTTP请求时,通常会涉及到`HttpURLConnection`、`HttpClient`或者第三方库如Apache HttpClient或者Spring的`RestTemplate`等。下面是一个基本的例子,展示如何使用`HttpURLConnection`发送这种类型的请求:
```java
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import javax.net.ssl.HttpsURLConnection;
import java.util.HashMap;
import java.util.Map;
public class MultipartRequest {
private static final String BOUNDARY = "-------------14737890123456789";
public void sendMultipartFile(String url, File file) throws IOException {
HttpURLConnection conn = null;
try {
// 创建连接
conn = (HttpsURLConnection) new URL(url).openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
// 添加文件数据到请求体
ByteArrayOutputStream baos = new ByteArrayOutputStream();
addPart(baos, "file", file.getName(), getInputStream(file));
byte[] requestBody = baos.toByteArray();
// 设置请求长度
long length = requestBody.length;
conn.setFixedLengthStreamingMode(length);
// 发送请求
conn.getOutputStream().write(requestBody);
// 获取响应
int responseCode = conn.getResponseCode();
System.out.println("Response Code : " + responseCode);
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
private InputStream getInputStream(File file) throws IOException {
return Files.newInputStream(file.toPath());
}
private void addPart(ByteArrayOutputStream outputStream, String fieldName, String fileName, InputStream inputStream) throws IOException {
byte[] endLine = ("\r\n--" + BOUNDARY + "\r\n").getBytes();
byte[] boundaryBytes = ("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"\r\n")
.getBytes();
outputStream.write(boundaryBytes);
outputStream.write("Content-Type: application/octet-stream\r\n".getBytes());
outputStream.write("\r\n".getBytes());
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.write(endLine);
}
}
```
在这个例子中,我们首先设置请求头的Content-Type,然后创建一个字节流来添加文件数据。文件数据由文件名、内容类型和文件内容组成,每部分数据之间通过边界标志分隔。
阅读全文