Java HttpURLConnection 使用java
/** * */ 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; /** * <p>描述:</p> * * @author saohuo * @date 2019年11月4日 * @version */ public class MultipartFormDataPost { // multipart/form-data; 表單各字段提交分隔符 private static String boundary = "--69695201314"; public void submit(Map<String, String> generalField, List<File> 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<String, String> 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); } }