HttpConnect上传文件和参数

模拟前端上传文件请求, 接口可用用MultipartFile来接收文件,其他参数就以方法入参形式接收。
 
public Object uploadFile(@RequestParam("file") MultipartFile file, String filePn){
    return null;
}
 
package com.hq.test.test;

import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class Test {

    private static String requestUrl = "http://localhost:8080/test/uploadFile";

    private static final int TIME_OUT = 8 * 1000;                          //超时时间
    private static final String CHARSET = "utf-8";                         //编码格式
    private static final String PREFIX = "--";                            //前缀
    private static final String BOUNDARY = UUID.randomUUID().toString();  //边界标识 随机生成
    private static final String CONTENT_TYPE = "multipart/form-data";     //内容类型
    private static final String LINE_END = "\r\n";                        //换行

    public static void main(String[] args) {
        Map fileMap = new HashMap();
        fileMap.put("Chrys.jpg", new File("D:\\Users\\Public\\Pictures\\Sample Pictures/Chrys.jpg"));

        Map strParams = new HashMap();
        strParams.put("filePn", 0);
        strParams.put("source", 13);

        String result = doPost(strParams, fileMap);
        System.out.println(result);
    }



    public static String doPost(final Map<String, Object> strParams, final Map<String, File> fileParams){

        HttpURLConnection conn = null;
        try {
            URL url = new URL(requestUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);//Post 请求不能使用缓存
            //设置请求头参数
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE+";boundary=" + BOUNDARY);
            /**
             * 请求体
             */
            //上传参数
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            //getStrParams()为一个
            dos.writeBytes( getStrParams(strParams).toString() );
            dos.flush();

            //文件上传
            StringBuilder fileSb = new StringBuilder();
            for (Map.Entry<String, File> fileEntry: fileParams.entrySet()){
                fileSb.append(PREFIX)
                        .append(BOUNDARY)
                        .append(LINE_END)
                        /**
                         * 这里重点注意: name里面的值为服务端需要的key 只有这个key 才可以得到对应的文件
                         * filename是文件的名字,包含后缀名的 比如:abc.png
                         */
                        .append("Content-Disposition: form-data; name=\"file\"; filename=\""
                                + fileEntry.getKey() + "\"" + LINE_END)
                        .append("Content-Type: image/jpg" + LINE_END) //此处的ContentType不同于 请求头 中Content-Type
                        .append("Content-Transfer-Encoding: 8bit" + LINE_END)
                        .append(LINE_END);// 参数头设置完以后需要两个换行,然后才是参数内容
                dos.writeBytes(fileSb.toString());
                dos.flush();
                InputStream is = new FileInputStream(fileEntry.getValue());
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = is.read(buffer)) != -1){
                    dos.write(buffer,0,len);
                }
                is.close();
                dos.writeBytes(LINE_END);
            }
            //请求结束标志
            dos.writeBytes(PREFIX + BOUNDARY + PREFIX + LINE_END);
            dos.flush();
            dos.close();

            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            return response.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (conn!=null){
                conn.disconnect();
            }
        }

        return "";
    }


    /**
     * 对post参数进行编码处理
     * */
    private static StringBuilder getStrParams(Map<String,Object> strParams){
        StringBuilder strSb = new StringBuilder();
        if(strParams != null && !strParams.isEmpty()){
            for (Map.Entry<String, Object> entry : strParams.entrySet() ){
                strSb.append(PREFIX)
                        .append(BOUNDARY)
                        .append(LINE_END)
                        .append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINE_END)
                        .append("Content-Type: text/plain; charset=" + CHARSET + LINE_END)
                        .append("Content-Transfer-Encoding: 8bit" + LINE_END)
                        .append(LINE_END)// 参数头设置完以后需要两个换行,然后才是参数内容
                        .append(entry.getValue())
                        .append(LINE_END);
            }
        }
        return strSb;
    }

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值