package snippet;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
public class HttpPostUtil {
private static String boundary = "--------httppost123";
// 发送数据到服务器,返回一个字节包含服务器的返回结果的数组
public static byte[] send(String urlString,Map<String, File[]> fileparams,Map<String, String> textParams) throws Exception {
DataOutputStream ds;
URL url = new URL(urlString);
HttpURLConnection conn;
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setConnectTimeout(10000); //连接超时为10秒
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
try {
conn.connect();
} catch (SocketTimeoutException e) {
// something
throw new RuntimeException();
}
ds = new DataOutputStream(conn.getOutputStream());
Set<String> keySetFile = fileparams.keySet();
for (Iterator<String> it = keySetFile.iterator(); it.hasNext();) {
String name = it.next();
File[] values = fileparams.get(name);
if(values == null || values.length == 0){
continue;
}
for(File value :values){
ds.writeBytes("--" + boundary + "\r\n");
ds.writeBytes("Content-Disposition: form-data; name=\"" + name
+ "\"; filename=\"" + encode(value.getName()) + "\"\r\n");
ds.writeBytes("Content-Type: " + getContentType(value) + "\r\n");
ds.writeBytes("\r\n");
ds.write(getBytes(value));
ds.writeBytes("\r\n");
}
}
Set<String> keySetText = textParams.keySet();
for (Iterator<String> it = keySetText.iterator(); it.hasNext();) {
String name = it.next();
String value = textParams.get(name);
ds.writeBytes("--" + boundary + "\r\n");
ds.writeBytes("Content-Disposition: form-data; name=\"" + name
+ "\"\r\n");
ds.writeBytes("\r\n");
ds.writeBytes(encode(value) + "\r\n");
}
ds.writeBytes("--" + boundary + "--" + "\r\n");
ds.writeBytes("\r\n");
InputStream in = conn.getInputStream();
int code = conn.getResponseCode();
if (code != 200) {
throw new Exception("请求" + urlString + "服务异常");
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
conn.disconnect();
return out.toByteArray();
}
//获取文件的上传类型,图片格式为image/png,image/jpg等。非图片为application/octet-stream
private static String getContentType(File f) throws Exception {
// return "application/octet-stream"; // 此行不再细分是否为图片,全部作为application/octet-stream 类型
ImageInputStream imagein = ImageIO.createImageInputStream(f);
if (imagein == null) {
return "application/octet-stream";
}
Iterator<ImageReader> it = ImageIO.getImageReaders(imagein);
if (!it.hasNext()) {
imagein.close();
return "application/octet-stream";
}
imagein.close();
return "image/" + it.next().getFormatName().toLowerCase();//将FormatName返回的值转换成小写,默认为大写
}
//把文件转换成字节数组
private static byte[] getBytes(File f) throws Exception {
FileInputStream in = new FileInputStream(f);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = in.read(b)) != -1) {
out.write(b, 0, n);
}
in.close();
return out.toByteArray();
}
// 对包含中文的字符串进行转码,此为UTF-8。服务器那边要进行一次解码
private static String encode(String value) throws Exception{
return URLEncoder.encode(value, "UTF-8");
}
public static void main(String[] args) throws Exception {
String urlString = "http://192.168.2.187/upload.shtml";
File [] files = new File[2];
files[0] = new File(
"C:/Users/Administrator/Desktop/2.png");
files[1] = new File(
"C:/Users/Administrator/Desktop/3.png");
Map<String, String> textParams = new HashMap<String, String>();
Map<String, File[]> fileparams = new HashMap<String, File[]>();
fileparams.put("files", files);
textParams.put("childDir", "shop");
byte[] b = HttpPostUtil.send(urlString,fileparams,textParams);
String result = new String(b);
System.out.println(result);
}
}
分享到:
相关推荐
由于iOS无法通过html表单来上传文件,因此想要上传文件,必须实现http请求,而不能像其他语言那样通过html表单的post就能上传。此demo经过xcode5测试通过。此文件上传demo是按照 rfc1867协议实现的。
http模拟POST表单上传文件 客户端是模拟POST表单提交数据 服务端负责接收上传的文件并保存到本地
JAVA模拟http上传文件_代码男_新浪博客
客户端文件续传上传到服务端,客户端http协议上传文件,客户端webserver上传文件,客户端续传,分割上传到服务器,模拟百度网盘文件上传 由于项目的需要一个客户端用来上传文件的,所以今天做了一个简单的例子
经过反复测试,绝对没有问题,而且提供完整的代码和类库
对于非安卓开发的接口开发人员,模拟请求上传文件用来调试接口。
通用的http请求工具,可以模拟表单提交、上传文件、发送请求、获取网页内容
模拟http请求实现文件上传,模拟doGet、doPost请求,实现信息发送
通过HTTP模拟GET或POST请求,提交数据到服务端获取响应,比较常见些;但如上传文件到服务端,使用html form当然简单了,而因环境所限有时需要使用模拟方法去提交有附件(文件上传)的表单。
android中模拟http协议表单上传.docx
Public c_strDestURL ' 文件上传URL http://127.0.0./upload_file.php Public c_strFileName ' 要上传的本地文件名 Public c_strFieldName ' 字段名,类似HTML表单Form中的input name Public c_strBoundary ' ...
采用JAVA的socket实现http协议,模拟浏览器访问服务端。
模拟客户端上传文件需要的jar,不是网页端上传,需要用到httpCilent和httpcore jar包
利用http协议传输大文件,其中包含: 1、QT编写的http server 2、python写的http client
CSharp客户端通过Http模拟表单提交到Java的web服务端.rar C#的wpf客户端使用HttpWebRequest模拟网页表单提交数据到Java的web服务端,Java服务端使用commons-fileupload.jar,Spring接受数据。 *******************...
1:base64加密传输数据,解决宽字符,中文传输数据问题 2:模拟表单实现多类型文件上传 3:vs2013开发,完整项目上传,下载即可完整运行
该代码实现了对于socket发送http请求上传文件的封装,且上传了一个模拟服务端的php代码,在 test目录,首先需要自己下载PHPStudy安装好,然后将下载下来的资源中test目录的文件复制到php目录下www目录中,启动...
.net通过HttpWebRequest模拟表单通过name/value形式提交参数和文件实例上传文件 通过HttpWebRequest类模拟网页请求,可向服务端提交多参数和多文件数据,参数和文件已key、value的形式进行上传。已集成完整的类库,...
strtus2+hibernate文件上传及连接数据库操作,使用模拟http请求测试的,验证类是updateTest类,文件上传类是uplodController,连接数据库的操作时productController类