httpurlconnection模拟post提交form表单(普通文本和上传文件) (
http://blog.sina.com.cn/s/blog_8417657f0101gvpc.html
用HttpUrlConnection模拟post表单进行文件上传平时很少使用,比较麻烦。
原理是: 分析文件上传的数据格式,然后根据格式构造相应的发送给服务器的字符串。
格式如下:这里的httppost123是我自己构造的字符串,可以是其他任何的字符串
----------httppost123 (\r\n)
Content-Disposition: form-data; name="img"; filename="t.txt"
(\r\n)
Content-Type: application/octet-stream (\r\n)
(\r\n)
sdfsdfsdfsdfsdf (\r\n)
----------httppost123 (\r\n)
Content-Disposition: form-data; name="text" (\r\n)
(\r\n)
text tttt (\r\n)
----------httppost123-- (\r\n)
(\r\n)
上面的(\r\n)表示各个数据必须以(\r\n)结尾。
package com.haitai.IntelligentAdapters.common;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpMultipartRequest {
//每个post参数之间的分隔
static final
String BOUNDARY =
"----MyFormBoundarySMFEtUYQG6r5B920"; //
定义数据分隔线
private
String urlStr; // 连接的地址
private
List<String[]>
strParams; // 文字post项集 strParams 1:key
2:value
private
List<String[]>
fileParams; // 文件的post项集 fileParams 1:fileField,
2.fileName, 3.fileType,
4.filePath
public
HttpMultipartRequest(String urlStr,
List<String[]> strParams,
List<String[]> fileParams)
{
this.urlStr = urlStr;
this.strParams = strParams;
this.fileParams = fileParams;
}
public
byte[] sendPost() throws Exception
{
HttpURLConnection hc = null; //http连接器
ByteArrayOutputStream
bos =
null;//byte输出流,用来读取服务器返回的信息
InputStream is =
null;//输入流,用来读取服务器返回的信息
byte[] res = null;//保存服务器返回的信息的byte数组
try {
URL url = new URL(urlStr);
hc = (HttpURLConnection)
url.openConnection();
hc.setRequestProperty("Content-Type", "multipart/form-data;
boundary=" + BOUNDARY);
hc.setRequestProperty("Charsert", "UTF-8");
// 发送POST请求必须设置如下两行
hc.setDoOutput(true);
hc.setDoInput(true);
hc.setUseCaches(false);
hc.setRequestMethod("POST");
OutputStream dout = hc.getOutputStream();
////1.先写文字形式的post流
//头
String boundary = BOUNDARY;
//中
StringBuffer resSB = new
StringBuffer("\r\n");
//尾
String endBoundary = "\r\n--" + boundary +
"--\r\n";
//strParams 1:key 2:value
if(strParams != null){
for(String[] parsm : strParams){
String key = parsm[0];
String value = parsm[1];
resSB.append("Content-Disposition: form-data;
name="").append(key).append(""\r\n").append("\r\n").append(value).append("\r\n").append("--").append(boundary).append("\r\n");
}
}
String boundaryMessage = resSB.toString();
//写出流
dout.write( ("--"+boundary+boundaryMessage).getBytes("utf-8")
);
//2.再写文件开式的post流
//fileParams 1:fileField, 2.fileName, 3.fileType,
4.filePath
resSB = new StringBuffer();
if(fileParams != null){
for(int i=0, num=fileParams.size(); i<num;
i++){
String[] parsm = fileParams.get(i);
String fileField = parsm[0];
String fileName = parsm[1];
String fileType = parsm[2];
String filePath = parsm[3];
resSB.append("Content-Disposition: form-data;
name="").append(fileField).append("";
filename="").append(
fileName).append(""\r\n").append("Content-Type:
").append(fileType).append("\r\n\r\n");
dout.write( resSB.toString().getBytes("utf-8")
);
//开始写文件
File file = new File(filePath);
DataInputStream in = new DataInputStream(new
FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024 * 5];
while ((bytes = in.read(bufferOut)) != -1)
{
dout.write(bufferOut, 0, bytes);
}
if(i<num-1){
dout.write( endBoundary.getBytes("utf-8")
);
}
in.close();
}
}
//3.最后写结尾
dout.write( endBoundary.getBytes("utf-8")
);
dout.close();
int ch;
is =
hc.getInputStream();
bos = new ByteArrayOutputStream();
while ((ch = is.read()) != -1) {
bos.write(ch);
}
res = bos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bos != null)
bos.close();
if (is != null)
is.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return res;
}
}
httpurlconnection模拟post提交form表单(普通文本和上传文件) (的更多相关文章
- Django框架 之 Form表单和Ajax上传文件
Django框架 之 Form表单和Ajax上传文件 浏览目录 Form表单上传文件 Ajax上传文件 伪造Ajax上传文件 Form表单上传文件 html 1 2 3 4 5 6 7 <h3& ...
- $_FILES参数详解及简单<form>表单无刷新上传文件
$_FILES:经由 HTTP POST 文件上传而提交至脚本的变量,类似于旧数组$HTTP_POST_FILES 数组(依然有效,但反对使用)详细信息可参阅 POST方法上传 $_FILES数组内容 ...
- C# 模拟提交 Form表单的数据
用 HttpWebRequest Post方法模拟提交Form表单数据时,需要设置 ContentType 为 "application/x-www-form-urlencoded" ...
- ajax提交form表单
1. ajax提交form表单和不同的form表单的提交主要区别在于,ajax提交表单是异步提交的,而普通的是同步提交的表单. 2. from视图部分 <form id="loginF ...
- Jquery通过Ajax方式来提交Form表单
今天刚好看到Jquery的ajax提交数据到服务器的方法,原文是: 保存数据到服务器,成功时显示信息. jQuery 代码: $.ajax({ type: "POST", url: ...
- ajax提交form表单资料详细汇总
一.ajax提交form表单和不同的form表单的提交主要区别在于,ajax提交表单是异步提交的,而普通的是同步提交的表单.通过在后台与服务器进行少量数据交换,ajax 可以使网页实现异步更新.这意味 ...
- 导出excel用ajax不行,提交form表单可以
导出excel用ajax不行,提交form表单可以. 一直用ajax找原因,网页不出现下载提示框 写了 response.setContentType("application/binary ...
- 提交form表单不刷新页面案列
提交form表单不刷新页面其实很简单的,这里拿上传图片来举列,大家有什么其它的方法也欢迎留言告知与我 <form action="" method="post&qu ...
- jquery实现ajax提交form表单的方法总结
本篇文章主要是对jquery实现ajax提交form表单的方法进行了总结介绍,需要的朋友可以过来参考下,希望对大家有所帮助 方法一: function AddHandlingFeeToRefund( ...
随机推荐
- Keepalived+NFS+SHELL脚本实现NFS-HA高可用
本来想做DRBD+HEARTBEAT,但是领导说再加硬盘浪费资源,没有必要,而且在已有硬盘上做风险较大,所以就只能用rsync来实现数据同步了,实验中发现很多的坑,都用脚本和计划任务给填上了,打算把这 ...
- 快速沃尔什变换 FWT
FWT 是处理位运算卷积的有效工具…… 原理……不懂,但背板子很简单,在这贴博客是为了放个模板,免得到时候忘记. 其中0为或卷积,1为与卷积,2为异或卷积…… void FWT(long long a ...
- hdu 1065(推公式)
I Think I Need a Houseboat Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Ja ...
- HDU 5988最小网络流(浮点数)
题目链接:http://acm.split.hdu.edu.cn/showproblem.php?pid=5988 哇,以前的模版一直T,加了优先队列优化才擦边过. 建图很好建,概率乘法化成概率加法不 ...
- 洛谷——P2176 [USACO14FEB]路障Roadblock
P2176 [USACO14FEB]路障Roadblock 题目描述 每天早晨,FJ从家中穿过农场走到牛棚.农场由 N 块农田组成,农田通过 M 条双向道路连接,每条路有一定长度.FJ 的房子在 1 ...
- android中添加只有border-left的样式
如何在android中的边框添加只有左边边框有颜色的样式呢 1. 相应的drawable文件 <?xml version="1.0" encoding="utf-8 ...
- HtmlEmail实现简单发送邮件
一般发送邮件的话系统项目中可能会用到,像一些通知信息自动发送等,会用到发送邮件的情况,发送邮件有好多种,包括设置各种格式,添加图片附件等,当然今天我们先看一下怎么实现发送成功. 工欲善其事必先利其器, ...
- spring ConfigurableListableBeanFactory 接口
接口继承关系如上图. ConfigurableListableBeanFactory具体: 1.2个忽略自动装配的的方法. 2.1个注册一个可分解依赖的方法. 3.1个判断指定的Bean是否有资格作为 ...
- MySql----on duplicate key
mysql on duplicate key 语句是解决key 冲突的问题,同时 ,key 包括 primary key 和 unique key 等
- 【java】google的zxing架包生成二维码和读取二维码【可带文字和logo】
承接RC4生成不重复字符串的需求之后,因为优惠码要方便用户使用的缘故,所以思来想去,觉得还是直接生成二维码给用户直接扫比较实用,也不用用户专门记录冗长的优惠码编号. ================= ...