/**
* java上传表单,有图片
* @param urlStr 上传地址
* @param textMap 表单参数
* @param fileMap 文件参数 key:文件名称 value:文件地址
* @return
*/
@SuppressWarnings("rawtypes")
public static String formUpload(String urlStr, Map<String, String> textMap,
Map<String, String> fileMap) {
String res = "";
HttpURLConnection conn = null;
// boundary就是request头和上传文件内容的分隔符
String BOUNDARY = "---------------------------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=" + 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(); //没有传入文件类型,同时根据文件获取不到类型,默认采用application/octet-stream
String contentType = new MimetypesFileTypeMap().getContentType(file);
//contentType非空采用filename匹配默认的图片类型
if(!"".equals(contentType)){
if (filename.endsWith(".png")) {
contentType = "image/png";
}else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {
contentType = "image/jpeg";
}else if (filename.endsWith(".gif")) {
contentType = "image/gif";
}else if (filename.endsWith(".ico")) {
contentType = "image/image/x-icon";
}
}
if (contentType == null || "".equals(contentType)) {
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;
}

java模拟from表单提交,上传图片的更多相关文章

  1. Java模拟POST表单提交HttpClient操作

    public static void Login() { String url = "http://www.***.com/login"; PostMethod postMetho ...

  2. 通过HttpURLConnection模拟post表单提交

    通过HttpURLConnection模拟post表单提交 package junit; import java.io.InputStream; import java.net.HttpURLConn ...

  3. js模拟form表单提交数据, js模拟a标签点击跳转,避开使用window.open引起来的浏览器阻止问题

    js模拟form表单提交数据, js模拟a标签点击跳转,避开使用window.open引起来的浏览器阻止问题 js模拟form表单提交数据源码: /** * js模拟form表单提交 * @param ...

  4. js_ajax模拟form表单提交_多文件上传_支持单个删除

    需求场景: 用一个input type="file"按钮上传多张图片,可多次上传,可单独删除,最后使用ajax模拟form表单提交功能提交到指定方法中: 问题:由于只有一个file ...

  5. Linux curl 模拟form表单提交信息和文件

    Linux curl 模拟form表单提交信息和文件   curl是一个命令行方式下传输数据的开源传输工具,支持多种协议:FTP.HTTP.HTTPS.IMAP.POP3.TELNET等,功能超级强大 ...

  6. jquery模拟form表单提交并新打开页面

    /** * form表单提交本页面打开 * @param url * @param params */ function postCurrent(url,params){ var form = $(& ...

  7. Ajax模拟Form表单提交,含多种数据上传

    ---恢复内容开始--- Ajax提交表单.使用FormData提交表单数据和上传的文件(这里的后台使用C#获取,你可以使用Java一样获取) 有时候前台的数据提交到后台,不想使用form表单上传,希 ...

  8. php 利用http上传协议(表单提交上传图片 )

    主要就是利用php 的 fsocketopen 消息传输. 这里先通过upload.html 文件提交,利用chrome抓包,可以看到几个关键的信息. 首先指定了表单类型为multipart/form ...

  9. C#模拟POST表单提交 --- WebClient

    string postString = "arg1=a&arg2=b";//这里即为传递的参数,可以用工具抓包分析,也可以自己分析,主要是form里面每一个name都要加进 ...

随机推荐

  1. (4)打造简单OS-loader硬盘加载和C++写入文件

    0.简要说明: 我们完全可以使用bochs创建映像文件,如https://blog.csdn.net/jadeshu/article/details/89046838   ,那么为什么还去用C++去模 ...

  2. 请写出一段python代码实现删除list里面的重复元素?

    l1 = ['b','c','d','c','a','a'] l2 = list(set(l1)) print(l2)

  3. 【2018.07.30】(广度优先搜索算法/队列)学习BFS算法小记

    一些BFS参考的博客: https://blog.csdn.net/ldx19980108/article/details/78641127 https://blog.csdn.net/u011437 ...

  4. SSM整合小结

    基本环境搭建 pom依赖 <dependencies> <!--Junit--> <dependency> <groupId>junit</gro ...

  5. Web安全测试 — 手工安全测试方法&修改建议

    常见问题 1.XSS(CrossSite Script)跨站脚本攻击 XSS(CrossSite Script)跨站脚本攻击.它指的是恶意攻击者往Web 页面里插入恶意 html代码,当用户浏览该页之 ...

  6. C++中的函数库

    函数库是由系统建立的具有一定功能的函数的集合. 库中存放函数的名称和对应的目标代码,以及连接过程中所需的重定位信息.用户也可以根据自己的需要建立自己的用户函数库. "cstdlib" ...

  7. PHP无限级树形结构算法(递归和引用)

    测试数组 $array = [ [, , 'name' => '这是主类'], [, , 'name' => '这是主类'], [, , 'name' => '父级为1子类'], [ ...

  8. [webpack]深入理解proxy代理

    1.一个基本的代理 module.exports = { //... devServer: { proxy: { '/api': 'http://localhost:3000' } } }; /api ...

  9. js Map对象的用法

    第一篇: Map: Map是一组键值对的结构,具有极快的查找速度. 举个例子,假设要根据同学的名字查找对应的成绩,如果用Array实现,需要两个Array: var names = ['Michael ...

  10. 【转载】 什么是P问题、NP问题和NPC问题

    原文地址: http://www.matrix67.com/blog/archives/105 转载地址: https://www.cnblogs.com/marsggbo/p/9360324.htm ...