JAVA 如何控制模拟表单提交_java后端模拟表单提交
代码可实现文本域及非文本域的处理
请求代码:
/**
* 上传
*
* @param urlStr
* @param textMap
* @param fileMap
* @return
*/
public static String formUpload(String urlStr, Map textMap,
Map 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) {
System.out.println("发送POST请求出错。" + urlStr);
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return res;
}
处理上传请求代码:
/**
* 上传
* @param request
* @param response
* @throws Exception
*/
public void doUpload(HttpServletRequest request, HttpServletResponse response)throws Exception {
String jsession = request.getParameter("jsessionid");
System.out.println(jsession);
HttpSession s = request.getSession();
System.out.println(s.getId());
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置内存缓冲区,超过后写入临时文件
factory.setSizeThreshold(10240000);
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置单个文件的最大上传值
upload.setFileSizeMax(10002400000l);
// 设置整个request的最大值
upload.setSizeMax(10002400000l);
upload.setHeaderEncoding("UTF-8");
//Date now = new Date();
Map map = new HashMap();
File tmpFile = new File(tmpFilePath);
if(!tmpFile.exists())
tmpFile.mkdirs();
List items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
throw new RuntimeException(e);
}
if (items == null)
return ;
Date date = new Date();
Iterator iter = items.iterator();
String fileName = tmpFilePath + File.separator +date.getTime();
while (iter.hasNext()) {// 循环获得每个表单项
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
String name = item.getFieldName();
try {
String value = item.getString("utf-8");// 如果参数里面有中文,防止出现乱码
map.put(name, value);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if(item.getName().length() > 0) {
String namefix = item.getName();
namefix = namefix.substring(namefix.lastIndexOf("."));
fileName = fileName +namefix;
item.write(new File(fileName));
}
}
String type =(String) map.get("type");
if(type.equals("war")){
request.getSession().setAttribute("warFileName",fileName);
}else if(type.equals("sql")){
request.getSession().setAttribute("sqlFileName",fileName);
}
try {
map.put("data", fileName);
response.getWriter().write(JsonUtils.convertToString(map));
} catch (IOException e) {
e.printStackTrace();
}
}
测试调用代码:
/**
* @param args
*/
public static void main(String[] args) {
String filepath="D:\\test\\PPGhost.war";
String urlStr = "http://localhost:8080/iopm/version/add.do?method=upload";
Map textMap = new HashMap();
textMap.put("name", "testname");
textMap.put("type", "war");
Map fileMap = new HashMap();
fileMap.put("userfile", filepath);
String ret = formUpload(urlStr, textMap, fileMap);
System.out.println(ret);
}
原文:http://www.cnblogs.com/teamobaby/p/4159640.html
JAVA 如何控制模拟表单提交_java后端模拟表单提交相关推荐
- java中的class 类的作用_Java中Class和单例类的作用与类成员的理解
Java中Class类的作用与深入理解 在程序运行期间,Java运行时系统始终为所有的对象维护一个被称为运行时的类型标识.这个信息跟踪着每个对象所属的类.JVM利用运行时信息选择相应的方法执行.而保存 ...
- java http 表单提交_java模仿http表单提交数据(含文件上传)实例源码
[实例简介]java模仿http表单提交数据.模仿http表单上传文件示例 [实例截图] [核心代码] package com.snca.cloudsign.main; import java.io. ...
- java实现顺序表和链表_Java: 实现顺序表和单链表的快速排序
快速排序 快速排序原理 快速排序(Quick Sort)的基本思想是,通过一趟排序将待排记录分割成独立的两部分,其中一部分记录的关键字均比另一部分记录的关键字小,则可对这两部分记录继续进行排序,以达到 ...
- java判断表是否存在_java怎么判断表是否存在?
在Java代码中判断数据库中某张表是否存在: 1.使用JdbcTemplate beanpublic boolean validateTableNameExist(String tableName) ...
- java模拟三人爬山_java笔记——模拟多人徒步爬山例子
模拟多人徒步爬山,使用多线程模拟多人徒步爬山训练要点,使用任意一种方式创建线程,使用 Thread.sleep()方法设置线程休眠.需求说明:每个线程代表一个人可设置每人爬山速度每爬完 100 米显示 ...
- java带头结点空单链表_Java版带头结点单链表的实现
Java版带头结点单链表的实现 Java版带头结点单链表的实现 package dsr; public interface IList { public void clear();//8 public ...
- java模拟多人接力赛跑_Java多线程--模拟接力赛跑
题目:模拟接力赛跑 需求说明: 1.多人参加1000米接力跑 2.每人跑100米,换下个选手 3.每跑10米显示信息 实现思路: 1.创建线程类RunThread 1.1多人共跑1000米,涉及多线程 ...
- Java模拟售票窗口代码_java多线程模拟售票,多个窗口售票
package com.ma.thread001; /** * 多线程模拟售票,多个窗口售票 * @author ma * */ public class SellTicktDemo implemen ...
- java 模拟简单打印机功能_java 单例模式模拟打印机打印任务
1.打印机报错处理类 package com.pattern06.singleton.sample03; public class PrintSpoolerException extends Exce ...
- java 九九乘法表倒叙_java九九乘法表倒三角输出
package test; public class Find { public static void main(String args[]){ int count=0; int k = 0; in ...
最新文章
- Android Dialog 关闭的时候标题栏闪烁一下的处理方法
- 剑桥的商学院硕士的创业项目找我做tech lead,稳得一批
- python读取excel送到网页_python+selenium excel中文读取填充到网页
- 各种实用的 PHP 开源库推荐
- 两个具有相同的名称在CLASSPATH中的类
- Redis的哨兵机制 或者心跳机制 模式 原理详解
- android 进度条 代码,Android进度条ProgressBar的实现代码
- android DatePicker
- Java基础:数组的声明,循环,赋值,拷贝。
- Bellman-Ford算法 - 有向图单源最短路径
- phpcms图库_love.php
- 让临时停车号码牌会说话--鲁哇客智能挪车号码牌技术升级之路
- c语言五子棋人工智能算法,五子棋人工智能算法实现研究,优化五子棋智能算法的思路...
- java 保存本地文件_java如何实现保存文件到本地
- Dyna中建立预紧力螺栓的两种方法
- 用JavaScript获取一年的天数
- ICDE‘22推荐系统论文之Research篇
- 计算机小知识140,电脑小知识140个小技巧(7)
- 利用PowerDesigner逆向工程抓取数据模型
- geohash java github_geohash