Cliente de carga de archivos para la operación de flujo de bytes de Java (HTTPS)

import inputoutput.stream.remote.util.SslUtil;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class UploadHttps {
    
    

    public static void main(String[] args) throws Exception {
    
    
        /**
         * 1、启动springboot-study项目(启动Server端)
         * 2、如需代理,需开启Fiddler
         */
        String url = "http://127.0.0.1:8080/upload";
        String body = "{\n" +
                "    \"AA\": {\n" +
                "        \"BB\": \"123123123123\",\n" +
                "        \"CC\":\"1\"\n" +
                "    }\n" +
                "}";
        List<String> fileList = new ArrayList<>();
        fileList.add("C:\\Users\\Administrator\\Desktop\\155.pdf");
        fileList.add("C:\\Users\\Administrator\\Desktop\\116.pdf");
        // 需开启代理(Fiddler)
        uploadFile2(body, fileList, url, new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8888)));
        receives();
    }

    private static final String DEFAULT_CHARSET = "utf-8";
    private static HttpsURLConnection conn = null;
    private static InputStream in = null;

    /**
     * 上传文件(form-data格式)
     *
     * @param body      请求报文
     * @param file      文件名
     * @param uploadUrl 上传地址
     * @param proxy     代理
     */
    public static void uploadFile2(String body, List<String> file, String uploadUrl, Proxy proxy) throws Exception {
    
    
        URL url = null;
        OutputStream out = null;
        try {
    
    
            // 构造URL
            url = new URL(uploadUrl);
            if (null != proxy) {
    
    
                // 忽略ssl证书不信任
                SslUtil.trustAllHttpsCertificates();
                // 打开连接
                conn = (HttpsURLConnection) url.openConnection(proxy);
            } else {
    
    
                conn = (HttpsURLConnection) url.openConnection();
            }
            // 发送Post请求(设置以下两个属性后才可以使用:conn.getInputStream().read();conn.getOutputStream().write() )
            conn.setDoInput(true);
            conn.setDoOutput(true);
            // 设置请求头参数(此处为示例,可更换,不需要可删除)
//            con.setRequestProperty("User-Agent", "PostmanRuntime/7.26.5");
//            con.setRequestProperty("Content-Type", "application/xml");
//            con.setRequestProperty("Accept", "*/*");
//            con.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
//            con.setRequestProperty("Connection", "keep-alive");
            // 设置请求超时为15s
            conn.setConnectTimeout(15 * 1000);
            // 设置请求方法
            conn.setRequestMethod("POST");

            String end = "\r\n";
            String twoHyphens = "--";
            String boundary = "--------------------------" + System.currentTimeMillis();
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            out = new DataOutputStream(conn.getOutputStream());

            if (null != body && !"".equalsIgnoreCase(body)) {
    
    
                StringBuilder sd = new StringBuilder();
                sd.append(twoHyphens + boundary + end);
                sd.append("Content-Disposition: form-data; name=\"params\"" + end + end);
                sd.append(body);
                sd.append(end);
                out.write(sd.toString().getBytes());
            }

            for (int i = 0; i < file.size(); i++) {
    
    
                StringBuilder fileSd = new StringBuilder();
                String filePath = file.get(i);
                String name = getFileName(filePath);
                fileSd.append(twoHyphens + boundary + end);
                //TODO: name="ss" :文件属性名需修改
                fileSd.append(String.format("Content-Disposition: form-data; name=\"file\"; filename=\"%s\"",
                        name) + end + end);
                out.write(fileSd.toString().getBytes());
                write(out, filePath);
                out.write(end.getBytes());
            }
            out.write((twoHyphens + boundary + twoHyphens + end).getBytes());
            out.flush();
        } catch (IOException e) {
    
    
            System.out.println("文件IO异常:" + e.getMessage());
            throw e;
        } catch (Exception e) {
    
    
            System.out.println("文件上传异常:" + e.getMessage());
            throw e;
        } finally {
    
    
            if (null != out) {
    
    
                out.close();
            }
        }
    }

    /**
     * 获取文件名
     *
     * @param filePath 文件全路径
     * @return
     */
    public static String getFileName(String filePath) {
    
    
        return new File(filePath).getName();
    }

    /**
     * 输出数据
     *
     * @param out      输出流
     * @param filePath 文件路径
     * @throws IOException
     */
    public static void write(OutputStream out, String filePath) throws IOException {
    
    
        File file = new File(filePath);
        DataInputStream in = null;
        try {
    
    
            in = new DataInputStream(new FileInputStream(file));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
    
    
                out.write(bufferOut, 0, bytes);
            }
        } catch (Exception e) {
    
    
            throw e;
        } finally {
    
    
            if (null != in) {
    
    
                in.close();
            }
        }
    }

    public static void receives() throws IOException {
    
    
        String charset = getResponseCharset(conn.getContentType());
        byte[] rbuf = null;
        InputStream es = conn.getErrorStream();
        try {
    
    
            in = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "ISO8859-1"));
            String line;
            StringBuffer buffer = new StringBuffer();
            while ((line = reader.readLine()) != null) {
    
    
                buffer.append(line);
            }
            rbuf = buffer.toString().getBytes("ISO8859-1");
        } catch (UnsupportedEncodingException e) {
    
    
            // TODO Auto-generated catch block
            throw e;
        } catch (IOException e) {
    
    
            // TODO Auto-generated catch block
            throw e;

        } finally {
    
    
            if (es != null) {
    
    
                try {
    
    
                    es.close();
                } catch (IOException e) {
    
    
                    throw e;
                }
            }
            if (in != null) {
    
    
                try {
    
    
                    in.close();
                } catch (IOException e) {
    
    
                    throw e;
                }
            }
            if (conn != null) {
    
    
                conn.disconnect();
            }
        }
        String res = new String(rbuf);
        System.out.println("receive:\n" + res);
    }

    private static String getResponseCharset(String ctype) {
    
    
        String charset = DEFAULT_CHARSET;
        if (null != ctype && !"".equals(ctype)) {
    
    
            String[] params = ctype.split(";");
            for (String param : params) {
    
    
                param = param.trim();
                if (param.startsWith("charset")) {
    
    
                    String[] pair = param.split("=", 2);
                    if (pair.length == 2) {
    
    
                        if (null != pair[1] && !"".equals(pair[1])) {
    
    
                            charset = pair[1].trim();
                        }
                    }
                    break;
                }
            }
        }
        return charset;
    }
}

Supongo que te gusta

Origin blog.csdn.net/zhangwenchao0814/article/details/109174023
Recomendado
Clasificación