后台模拟POST上传整合
简介:Java后台模拟post请求,发送参数以及上传文件等方式,适用有些公众API接口的调用.
发送请求
后台
package org.lives.platform.upload.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 javax.activation.MimetypesFileTypeMap;
import org.junit.Test;
import org.liufeng.weixin.pojo.AccessToken;
import org.liufeng.weixin.util.WeixinUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class HttpPostUploadUtil {
/**
* @param args
*/
public static void main(String[] args) {
//要上传的文件地址
String filepath = "F:\\2.png";
String urlStr = "http://localhost:8080/wxchar_menu/upload";
Map<String, String> textMap = new HashMap<String, String>();
textMap.put("name", "testname");
Map<String, String> fileMap = new HashMap<String, String>();
//随便写入的参数
fileMap.put("userfile", filepath);
String ret = formUpload(urlStr, textMap, fileMap);
System.out.println(ret);
}
/**
*
* @param urlStr
* @param textMap
* @param fileMap
* @return
*/
public static String formUpload(String urlStr, Map<String, String> textMap,
Map<String, String> fileMap) {
String res = "";
HttpURLConnection conn = null;
String BOUNDARY = "---------------------------123821742118716"; // boundary就是request头和上传文件内容的分隔符
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=" + BOUNDARY);
OutputStream out = new DataOutputStream(conn.getOutputStream());
// text
if (textMap != null) {
StringBuffer strBuf = new StringBuffer();
Iterator iter = textMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
if (inputValue == null) {
continue;
}
strBuf.append("\r\n").append("--").append(BOUNDARY)
.append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\""
+ inputName + "\"\r\n\r\n");
strBuf.append(inputValue);
}
out.write(strBuf.toString().getBytes());
}
// file
if (fileMap != null) {
Iterator iter = fileMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.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();
String contentType = new MimetypesFileTypeMap()
.getContentType(file);
if (filename.endsWith(".png")) {
contentType = "image/png";
}
if (contentType == null || contentType.equals("")) {
contentType = "application/octet-stream";
}
StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(BOUNDARY)
.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--" + BOUNDARY + "--\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");
}
res = strBuf.toString();
reader.close();
reader = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return res;
}
}
这样的效果就相当于是页面上的:
<form action="/wxchar_menu/upload" method="post"
enctype="multipart/form-data">
<label> <input type="text" name="name" value="name" />
</label> <label> <input type="file" name="userfile" />
</label> <label> <input type="submit" value="up" />
</label>
</form>
后台接受
package org.lives.platform.upload.utils;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class ManageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String title = request.getParameter("title");
String timelength = request.getParameter("timelength");
System.out.println("视频名称:" + title);
System.out.println("时长:" + timelength);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
try {
FileItemFactory factory = new DiskFileItemFactory();
// File filetemp = new File("d:/a");
// if(!filetemp.exists()){filetemp.mkdirs();}
// factory.setRepository(new File("d:/a"));
// //设置临时目录
// factory.setSizeThreshold(1024*8);
// //8k的缓冲区,文件大于8K则保存到临时目录
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
// upload.setFileSizeMax(1024 * 1024 * 10*2);//
// 设置每个文件最大为20M
// upload.setSizeMax(1024 * 1024 * 100);//
// 一共最多能上传100M
List<FileItem> items = upload.parseRequest(request);
String dir = request.getSession().getServletContext()
.getRealPath("/files");
// File dirFile = new File(dir);
//存在了本地e盘下面
File dirFile = new File("e://downFiles");
if (!dirFile.exists())
dirFile.mkdirs();
for (FileItem item : items) {
if (item.isFormField()) {// 如果文本类型参数
String name = item.getFieldName();
String value = item.getString("UTF-8");
System.out.println(name + "=" + value);
} else {// 如果文件类型参数
System.out.println(dir);
File saveFile = new File(dirFile, item.getName());
item.write(saveFile);
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
doGet(request, response);
}
}
}
需要的jar
http://download.youkuaiyun.com/detail/u014201191/8829429