java模拟http请求,同时上传多个文件和参数(客户端)

package com.acconsys.base.util;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class HttpRequester {
    private static final String BOUNDARY = "-------45962402127348";
    private static final String FILE_ENCTYPE = "multipart/form-data";
public static void main(String[] args) {
	String filepath = "D:\\360安全浏览器下载\\plsqldev_2990.zip";
	String urlStr = "http://localhost:8080/chsService/FileUploadServlet";
	Map<String, String> textMap = new HashMap<String, String>();
	textMap.put("hahaha", "Capital-DocGen.zip");
	textMap.put("aaa", "D:\\server.zip");
	textMap.put("bbbb", "<?xml version='1.0' encoding='utf-8'?><root><parts><part number='设计Name' name='设计ShortDescription'  projectName='项目名'  version='设计版本' owner='设计创建人' type='设计类型' domain='所属域Name' status='设计状态'></part><part number='设计Name' name='设计ShortDescription'  projectName='项目名'  version='设计版本' owner='设计创建人' type='设计类型' domain='所属域Name' status='设计状态'></part><part number='设计Name' name='设计ShortDescription'  projectName='项目名'  version='设计版本' owner='设计创建人' type='设计类型' domain='所属域Name' status='设计状态'></part></parts></root>");
	Map<String, File> fileMap = new HashMap<String, File>();
	fileMap.put("myFile.zip", new File(filepath));
	post(urlStr, textMap, fileMap);

}
/**
 * 
 * @param urlStr http请求路径
 * @param params 请求参数
 * @param images 上传文件
 * @return
 */
    public static InputStream post(String urlStr, Map<String, String> params,
            Map<String, File> images) {
        InputStream is = null;
        
        try {
            URL url = new URL(urlStr);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            con.setConnectTimeout(5000);
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
            con.setRequestMethod("POST");
            con.setRequestProperty("Connection", "Keep-Alive");
            con.setRequestProperty("Charset", "UTF-8");
            con.setRequestProperty("Content-Type", FILE_ENCTYPE + "; boundary="
                    + BOUNDARY);
            
            StringBuilder sb = null;
            DataOutputStream dos = new DataOutputStream(con.getOutputStream());;
            if (params != null) {
                sb = new StringBuilder();
                for (String s : params.keySet()) {
                    sb.append("--");
                    sb.append(BOUNDARY);
                    sb.append("\r\n");
                    sb.append("Content-Disposition: form-data; name=\"");
                    sb.append(s);
                    sb.append("\"\r\n\r\n");
                    sb.append(params.get(s));
                    sb.append("\r\n");
                }
    
                dos.write(sb.toString().getBytes());
            }

            if (images != null) {
                for (String s : images.keySet()) {
                    File f = images.get(s);
                    sb = new StringBuilder();
                    sb.append("--");
                    sb.append(BOUNDARY);
                    sb.append("\r\n");
                    sb.append("Content-Disposition: form-data; name=\"");
                    sb.append(s);
                    sb.append("\"; filename=\"");
                    sb.append(f.getName());
                    sb.append("\"\r\n");
                    sb.append("Content-Type: application/zip");//这里注意!如果上传的不是图片,要在这里改文件格式,比如txt文件,这里应该是text/plain
                    sb.append("\r\n\r\n");
                    dos.write(sb.toString().getBytes());
    
                    FileInputStream fis = new FileInputStream(f);
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = fis.read(buffer)) != -1) {
                        dos.write(buffer, 0, len);
                    }
                    dos.write("\r\n".getBytes());
                    fis.close();
                }
    
                sb = new StringBuilder();
                sb.append("--");
                sb.append(BOUNDARY);
                sb.append("--\r\n");
                dos.write(sb.toString().getBytes());
            }
            dos.flush();

            if (con.getResponseCode() == 200)
                is = con.getInputStream();
            
            dos.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
}

 

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值