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;
}
}