java发送multipart/form-data格式的数据 的demo
时间: 2023-07-19 13:51:53 浏览: 113
C#使用multipart/form-data示例
以下是Java发送multipart/form-data格式数据的示例代码:
```java
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MultipartFormDataDemo {
public static void main(String[] args) {
String url = "http://example.com/upload";
String charset = "UTF-8";
String boundary = Long.toHexString(System.currentTimeMillis());
try {
URL uploadUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) uploadUrl.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
// 添加上传文件
File file = new File("path/to/file");
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()];
fileInputStream.read(buffer);
fileInputStream.close();
outputStream.writeBytes("--" + boundary + "\r\n");
outputStream.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n");
outputStream.writeBytes("Content-Type: application/octet-stream\r\n\r\n");
outputStream.write(buffer);
outputStream.writeBytes("\r\n");
// 添加其他参数
outputStream.writeBytes("--" + boundary + "\r\n");
outputStream.writeBytes("Content-Disposition: form-data; name=\"param1\"\r\n\r\n");
outputStream.writeBytes("value1\r\n");
outputStream.writeBytes("--" + boundary + "\r\n");
outputStream.writeBytes("Content-Disposition: form-data; name=\"param2\"\r\n\r\n");
outputStream.writeBytes("value2\r\n");
outputStream.writeBytes("--" + boundary + "--\r\n");
outputStream.flush();
outputStream.close();
// 读取服务器响应
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
注意事项:
- Content-Type 头部必须设置为 multipart/form-data,并且包含一个 boundary 参数,boundary 是一个随机字符串,用于分隔不同的部分。
- 文件和其他参数都需要使用 multipart/form-data 格式进行发送。
- 每个部分必须以 --boundary 开始,以 --boundary-- 结束,并且每个部分之间需要用 \r\n 分隔。
阅读全文