java发送post请求,使用multipart/form-data格式文件数据到接口
在Java中,你可以使用HttpURLConnection
或者第三方库如Apache HttpClient来发送POST请求。以下是使用HttpURLConnection
发送带有文件的multipart/form-data
请求的示例代码:
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class MultipartFormDataExample {
public static void main(String[] args) {
String boundary = Long.toHexString(System.currentTimeMillis());
String CRLF = "\r\n"; // 换行符
String charset = "UTF-8"; // 设置编码
URL url = null;
HttpURLConnection connection = null;
OutputStream outputStream = null;
InputStream inputStream = null;
try {
url = new URL("http://your-api-endpoint.com"); // 替换为你的API端点
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
outputStream = connection.getOutputStream();
outputStream.write(("--" + boundary + CRLF).getBytes(charset));
outputStream.write(String.format("Content-Disposition: form-data; name=\"file\"; filename=\"%s\"%s", "file.txt", CRLF).getBytes(charset));
outputStream.write(String.format("Content-Type: %s%s", "text/plain", CRLF).getBytes(charset));
outputStream.write(CRLF.getBytes(charset));
// 写入文件内容
File file = new File("path/to/your/file.txt"); // 替换为你的文件路径
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
fileInputStream.close();
// 结束multipart数据
outputStream.write(
评论已关闭