import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.UUID;
public class MyHttpUploader {
/**
* 使用HttpURLConnection通过POST方式提交请求,并上传文件。
*
* @param actionUrl
* 访问的url
* @param textParams
* 文本类型的POST参数(key:value)
* @param filePaths
* 文件路径的集合
* @return 服务器返回的数据,出现异常时返回 null
*/
public static String httpPostWithFiles(String actionUrl, Map<String, String> textParams, List<String> filePaths) {
BufferedReader br = null;
DataOutputStream outStream = null;
HttpURLConnection conn = null;
InputStream is=null;
try {
final String BOUNDARY = UUID.randomUUID().toString();
final String PREFIX = "--";
final String LINE_END = "\r\n";
final String MULTIPART_FROM_DATA = "multipart/form-data";
final String CHARSET = "UTF-8";
URL uri = new URL(actionUrl);
conn = (HttpURLConnection) uri.openConnection();
// 缓存大小
conn.setChunkedStreamingMode(1024 * 64);
// 超时
conn.setReadTimeout(50 * 1000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
// 拼接文本类型的参数
StringBuilder textSb = new StringBuilder();
if (textParams != null && textParams.size()>0) {
for (Map.Entry<String, String> entry : textParams.entrySet()) {
textSb.append(PREFIX).append(BOUNDARY).append(LINE_END);
textSb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINE_END);
textSb.append("Content-Type: text/plain; charset=" + CHARSET + LINE_END);
textSb.append("Content-Transfer-Encoding: 8bit" + LINE_END);
textSb.append(LINE_END);
textSb.append(entry.getValue());
textSb.append(LINE_END);
}
}
outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(textSb.toString().getBytes());
//System.out.println(textSb.toString());
// 发送文件数据
if (filePaths != null && filePaths.size()>0) {
for (int i = 0; i < filePaths.size(); i++) {
String _filePath = filePaths.get(i);
StringBuilder fileSb = new StringBuilder();
fileSb.append(PREFIX).append(BOUNDARY).append(LINE_END);
fileSb.append("Content-Disposition: form-data; name=\"files" + (i + 1) + "\"; filename=\""
+ _filePath.substring(_filePath.lastIndexOf("/") + 1) + "\"" + LINE_END);
fileSb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
fileSb.append(LINE_END);
//System.out.println(fileSb.toString());
outStream.write(fileSb.toString().getBytes());
is = new FileInputStream(_filePath);
byte[] buffer = new byte[1024 * 8];
int len;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
outStream.write(LINE_END.getBytes());
}
}
// 请求结束标志
outStream.write((PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes());
outStream.flush();
// 得到响应码
int responseCode = conn.getResponseCode();
br = new BufferedReader(new InputStreamReader(conn.getInputStream(), CHARSET));
StringBuilder resultSb = null;
String line;
if (responseCode == 200) {
resultSb = new StringBuilder();
while ((line = br.readLine()) != null) {
resultSb.append(line).append("\n");
}
}
return resultSb == null ? null : resultSb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outStream != null) {
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (conn != null) {
conn.disconnect();
}
}
return null;
}
}
下面的测试类
package sy.controller.news;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import sy.common.exception.LcsTipException;
import sy.util.HttpClientUtils;
import sy.util.MD5;
public class Main {
public static void main(String[] args) throws Exception {
main2();
}
public static void main2() {
String url="http://localhost/demoWeb/fileUpload/fileAccept.do";
List<String> filePathsList=new ArrayList<String>();
filePathsList.add("C:\\aa\\bb\\eee.png");
filePathsList.add("C:\\aa\\bb\\shala2016.png");
Map<String, String> params=new HashMap<String, String>();
params.put("content", "这里是content内容哦");
params.put("mobile", "185XXXXXXXX");
String aaa=new MyHttpUploader().httpPostWithFiles(url, params, filePathsList);
System.out.println("返回结果:"+aaa);
}
}