HttpURLConnection 提交表單+ 上傳檔案
阿新 • • 發佈:2019-01-07
package com.customUpload.utils; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import net.sf.jmimemagic.Magic; import net.sf.jmimemagic.MagicMatch; public class HttpUploadUtil { public static void main(String[] args) { //檔名 String filepath = "C:\\a.gif"; //請求地址 String urlStr = "http://localhost:8888/CustomUpload/CustomUploadAction!imgUpload.do"; Map<String, String> fieldMap = new HashMap<String, String>(); //表單欄位對映 fieldMap.put("upFileFileName", "a.gif"); //要上傳的檔案 Map<String, String> filesMap = new HashMap<String, String>(); filesMap.put("upFile", filepath); String result = uploadFormFile(urlStr, fieldMap, filesMap); System.out.println(result); } /** * 上傳圖片form * @param urlStr 地址 * @param textMap form欄位型別 * @param fileMap 檔案上傳map * @return * @author wall * @date 2015-8-6 */ public static String uploadFormFile(String urlStr, Map<String, String> textMap, Map<String, String> fileMap) { String result = ""; HttpURLConnection conn = null; //分隔符 String finalSplit = "---------------------------123821742118716"; try { URL url = new URL(urlStr); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(30000); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + finalSplit); OutputStream out = new DataOutputStream(conn.getOutputStream()); //文字域 if (textMap != null) { StringBuffer strBuf = new StringBuffer(); Iterator<Map.Entry<String, String>> iter = textMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = iter.next(); String inputName = (String) entry.getKey(); String inputValue = (String) entry.getValue(); if (inputValue == null) { continue; } inputValue = new String(inputValue.getBytes("GBK")); strBuf.append("\r\n").append("--").append(finalSplit).append("\r\n"); strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n"); strBuf.append(inputValue); } out.write(strBuf.toString().getBytes("UTF-8")); } // 上傳檔案 if (fileMap != null) { Iterator<Map.Entry<String, String>> iter = fileMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = iter.next(); String inputName = (String) entry.getKey(); String inputValue = (String) entry.getValue(); if (inputValue == null) { continue; } File file = new File(inputValue); String filename = file.getName(); MagicMatch match = Magic.getMagicMatch(file, false, true); String contentType = match.getMimeType(); StringBuffer strBuf = new StringBuffer(); strBuf.append("\r\n").append("--").append(finalSplit).append("\r\n"); strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n"); strBuf.append("Content-Type:" + contentType + "\r\n\r\n"); out.write(strBuf.toString().getBytes()); DataInputStream in = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } in.close(); } } byte[] endData = ( "\r\n--" + finalSplit + "--\r\n").getBytes(); out.write(endData); out.flush(); out.close(); // 讀取返回資料 StringBuffer strBuf = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { strBuf.append(line).append("\n"); } result = strBuf.toString(); reader.close(); reader = null; } catch (Exception e) { System.out.println("上傳檔案請求失敗!" + urlStr); e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); conn = null; } } return result; } }