Java HttpURLConnection 使用
/**
*
*/
package com.demo.java;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
/**
*
描述:
*
* @author saohuo
* @date 2019年11月4日
* @version
*/
public class MultipartFormDataPost {
// multipart/form-data; 表单各字段提交分隔符
private static String boundary = "--69695201314";
public void submit(Map generalField, List files) throws Exception {
HttpURLConnection connection = null;
OutputStream os = null;
URL url = new URL("http:");
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("content-type", "multipart/form-data;boundary="+boundary);
os = new DataOutputStream(connection.getOutputStream());
// 文本参数组装
StringBuffer textFormBody = new StringBuffer();
Map formField = generalField;
formField.forEach((k,v) -> {
textFormBody.append("\r\n").append("--").append(boundary).append("\r\n");
textFormBody.append("Content-Disposition: form-data; name=\""+k+"\"");
textFormBody.append("\r\n\r\n");//名称与数据之间要有两个回车换行
textFormBody.append(v);
});
// 提交文本表单
os.write(textFormBody.toString().getBytes("UTF-8"));
// 文件数据
if (files != null && !files.isEmpty()) {
int fileIndex = 0;
for(File file : files) {
String filename = file.getName();
String fileMinetype = URLConnection.getFileNameMap().getContentTypeFor(filename);
StringBuffer fileFormBody = new StringBuffer();
fileFormBody.append("\r\n").append("--").append(boundary).append("\r\n");
fileFormBody.append("Content-Disposition: form-data; name=\"files["+fileIndex+"]\"; filename=\"" + filename + "\"");
fileFormBody.append("\r\n");
fileFormBody.append("Content-Type:" + fileMinetype);
fileFormBody.append("\r\n\r\n");
// 提交文件基本信息(文件名、文件长度、文件类型等)
os.write(fileFormBody.toString().getBytes());
InputStream fileStream = new FileInputStream(file);
DataInputStream fileDataIs = new DataInputStream(fileStream);
int filebytes = 0;
byte[] filebufferOut = new byte[1024];
while ((filebytes = fileDataIs.read(filebufferOut)) != -1) {
os.write(filebufferOut, 0, filebytes);
}
fileDataIs.close();
fileIndex++;
}
} // 文件写入结束
// 最后写入结束标识
byte[] endBodyData = ("\r\n--" + boundary + "--\r\n").getBytes();
os.write(endBodyData);
os.flush();
int responseCode = connection.getResponseCode();
// 提交结果状态码
System.out.println(responseCode);
}
}