post请求模仿表单上传文件

public class UploadFile {

    public static void main(String[] args) {
        File file = new File("/Users/icon/101_1.png");
        Map<String, String> params = new HashMap<>();
        params.put("token", "oh, it's ok");
//        String s = uploadFileStream("url", "icon.png", params, new HashMap<>());
//        System.out.println(s);
    }


    /**
     * 上传文件流到指定Url
     * @param url  上传地址
     * @param fileName    上传到服务的文件名
     * @param fileInputStream    流
     * @param params    其它参数集合
     * @param header    请求头
     * @return
     */
    public static String uploadFileStream(String url, String fileName, InputStream fileInputStream, Map<String, String> params, Map<String, String> header) {

        String message = "";
        String boundary = "******";        //随机分割线

        InputStream inputStream = null;
        OutputStream outputStream = null;
        HttpURLConnection connection = null;
        try {
            URL url1 = new URL(url);
            connection = (HttpURLConnection) url1.openConnection();
            connection.setRequestMethod("POST");
            connection.addRequestProperty("Connection", "Keep-Alive");
            connection.addRequestProperty("Charset", "UTF-8");
            connection.addRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

            //添加请求头
            for (Map.Entry<String, String> entry : header.entrySet()) {
                connection.addRequestProperty(entry.getKey(), entry.getValue());
            }

            // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在
            // http正文内,因此需要设为true, 默认情况下是false;
            connection.setDoOutput(true);
            //设置是否从httpUrlConnection读入,默认情况下是true;
            connection.setDoInput(true);
            // Post 请求不能使用缓存  ?
            connection.setUseCaches(false);
            connection.setConnectTimeout(20000);
            outputStream = connection.getOutputStream();
            StringBuilder sb = new StringBuilder();
            sb.append("--" + boundary + "\r\n")
                    .append("Content-Disposition: form-data; name=\"file\"; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"\r\n")
                    .append("Content-Type: application/pdf" + "\r\n")
                    .append("\r\n");
				/*outputStream.write(("--" + boundary + "\r\n").getBytes("utf-8"));

				// 设定传送的内容类型是可序列化的java对象
				// (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
				outputStream.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + URLEncoder.encode(file.getName(), "UTF-8") + "\"\r\n").getBytes("utf-8"));
				outputStream.write(("Content-Type: application/pdf"+"\r\n").getBytes("utf-8"));*/
            outputStream.write(sb.toString().getBytes("utf-8"));
            byte[] b = new byte[1024];
            while ((fileInputStream.read(b)) != -1) {
                outputStream.write(b);
            }
            outputStream.write(("\r\n").getBytes("utf-8"));
            //数据上传
            for (Map.Entry<String, String> entry : params.entrySet()) {
                sb.append("\r\n")
                        .append("--" + boundary + "\r\n")
                        .append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n")
                        .append("\r\n")
                        .append(entry.getValue() + "\r\n");
            }
            sb.append("--" + boundary + "--" + "\r\n");
            outputStream.write(sb.toString().getBytes("utf-8"));

            if (connection.getResponseCode() >= 300) {
                throw new Exception("HTTP Request is not success, Response code is " + connection.getResponseCode());
            }


            if (connection.getResponseCode() == 200) {

                inputStream = connection.getInputStream();
                Reader reader = new InputStreamReader(inputStream, "utf-8");
                StringBuilder response = new StringBuilder();

                final char[] buff = new char[1024];
                int read = 0;
                while ((read = reader.read(buff)) > 0) {
                    response.append(buff, 0, read);
                }

                return response.toString();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            connection.disconnect();

        }
        return message;
    }


    /**
     * 上传文件到指定Url
     *
     * @param url    请求地址
     * @param file   上传文件
     * @param params 其他参数集合
     * @param header 请求头
     * @return
     */
    public static String uploadFile(String url, File file, Map<String, String> params, Map<String, String> header) {

        String message = "";
        String boundary = "******";        //随机分割线

        InputStream inputStream = null;
        FileInputStream fileInputStream = null;
        OutputStream outputStream = null;
        HttpURLConnection connection = null;
        try {
            URL url1 = new URL(url);
            connection = (HttpURLConnection) url1.openConnection();
            connection.setRequestMethod("POST");
            connection.addRequestProperty("Connection", "Keep-Alive");
            connection.addRequestProperty("Charset", "UTF-8");
            connection.addRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

            //添加请求头
            for (Map.Entry<String, String> entry : header.entrySet()) {
                connection.addRequestProperty(entry.getKey(), entry.getValue());
            }

            // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在
            // http正文内,因此需要设为true, 默认情况下是false;
            connection.setDoOutput(true);
            //设置是否从httpUrlConnection读入,默认情况下是true;
            connection.setDoInput(true);
            // Post 请求不能使用缓存  ?
            connection.setUseCaches(false);
            connection.setConnectTimeout(20000);
            outputStream = connection.getOutputStream();

            StringBuilder sb = new StringBuilder();
            if (file != null) {
                //文件上传
                fileInputStream = new FileInputStream(file);
                sb.append("--" + boundary + "\r\n")
                        .append("Content-Disposition: form-data; name=\"file\"; filename=\"" + URLEncoder.encode(file.getName(), "UTF-8") + "\"\r\n")
                        .append("Content-Type: application/pdf" + "\r\n")
                        .append("\r\n");
				/*outputStream.write(("--" + boundary + "\r\n").getBytes("utf-8"));

				// 设定传送的内容类型是可序列化的java对象
				// (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
				outputStream.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + URLEncoder.encode(file.getName(), "UTF-8") + "\"\r\n").getBytes("utf-8"));
				outputStream.write(("Content-Type: application/pdf"+"\r\n").getBytes("utf-8"));*/
                outputStream.write(sb.toString().getBytes("utf-8"));
                byte[] b = new byte[1024];
                while ((fileInputStream.read(b)) != -1) {
                    outputStream.write(b);
                }
                outputStream.write(("\r\n").getBytes("utf-8"));
            }

            //数据上传
            for (Map.Entry<String, String> entry : params.entrySet()) {
                sb.append("\r\n")
                        .append("--" + boundary + "\r\n")
                        .append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n")
                        .append("\r\n")
                        .append(entry.getValue() + "\r\n");
            }
            sb.append("--" + boundary + "--" + "\r\n");
            outputStream.write(sb.toString().getBytes("utf-8"));

            if (connection.getResponseCode() >= 300) {
                throw new Exception("HTTP Request is not success, Response code is " + connection.getResponseCode());
            }


            if (connection.getResponseCode() == 200) {

                inputStream = connection.getInputStream();
                Reader reader = new InputStreamReader(inputStream, "utf-8");
                StringBuilder response = new StringBuilder();

                final char[] buff = new char[1024];
                int read = 0;
                while ((read = reader.read(buff)) > 0) {
                    response.append(buff, 0, read);
                }

                return response.toString();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            connection.disconnect();

        }
        return message;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值