HttpURLConnection download file, byte array POST multipart/form-data

View POST multipart/form-data protocol format

The downloaded file is stored in a byte array and POST multipart/form-data interface

package com.http;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class HttpDownload {
    /**
     *
     * @param urlPath download path
     * @param downloadDir download storage directory
     * @return Return to download file
     */
    public static byte[] downloadFile(String urlPath, String downloadDir, String fileName) {
        BufferedInputStream in = null;
        OutputStream out = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlPath);
            connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Type", "application/octet-stream;charset=utf-8");
            connection.setRequestProperty("Connection", "close");
            connection.setConnectTimeout(5000);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.connect();

            // File size
            int fileLength = connection.getContentLength();
            System.out.println("file length-------------" + fileLength + " (byte)");
            in = new BufferedInputStream(connection.getInputStream());
            String path = downloadDir + File.separatorChar + fileName;
            //Download file to local
            File file = new File(path);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            out = new FileOutputStream(file);
            int size = 0;
            int len = 0;
            byte[] buf = new byte[1024 * 1024];
            byte[] data = new byte[fileLength];
            int dataPos = 0;
            while ((size = in.read(buf)) != -1) {
                len + = size;
                out.write(buf, 0, size);
                for (int i = 0; i < size; i + + ) {
                    data[dataPos] = buf[i];
                    dataPos + + ;
                }
            }
            System.out.println("download finish--" + fileLength + "," + len + "," + dataPos + " (byte)");
            return data;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(in, out);
            closeConnection(connection);
        }
        return new byte[0];
    }

    public static String uploadFile(String actionUrl, Map<String, String> textMap, String filekey, byte[] data,
        String fileName) {
        String end = "\r\\
";
        String boundary = "----WebKitFormBoundaryLBFuobxXx0AmQVFR";
        DataOutputStream out = null;
        BufferedReader reader = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(actionUrl);
            connection = (HttpURLConnection)url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "close");
            connection.setRequestProperty("Charset", "utf-8");
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            out = new DataOutputStream(connection.getOutputStream());

            // Process text ==============================
            String strData = "";
            if (textMap != null) {
                Iterator<Map.Entry<String, String>> iter = textMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry<String, String> entry = iter.next();
                    String name = (String)entry.getKey();
                    String value = (String)entry.getValue();
                    if (value == null) {
                        continue;
                    }
                    value = new String(value.getBytes("utf-8"));
                    strData = end + "--" + boundary + end;
                    System.out.println(strData);
                    out.writeBytes(strData);
                    strData = "Content-Disposition: form-data; name="" + name + """ + end + end + value;
                    System.out.println(strData);
                    out.writeBytes(strData);
                }
            }
            //End of text processing==============================
            // Start uploading files ========================================
            strData = end + "--" + boundary + end;
            System.out.println(strData);
            out.writeBytes(strData);
            strData =
                "Content-Disposition: form-data;" + " name="" + filekey + ""; filename="" + fileName + "" " + end;
            System.out.println(strData);
            out.writeBytes(strData);
            strData = "Content-Type:" + " text/plain" + end + end;
            System.out.println(strData);
            out.writeBytes(strData);
            System.out.println("binary...");
            out.write(data);
            System.out.println(end);
            out.writeBytes(end);
            strData = "--" + boundary + "--" + end;
            System.out.println(strData);
            //End of uploading files========================================
            // Request end flag
            out.writeBytes(strData);
            out.flush();

            // Get response
            if (connection.getResponseCode() >= 300) {
                throw new Exception("HTTP Request fail,response code " + connection.getResponseCode());
            }
            StringBuilder sb = new StringBuilder();
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String strLine = null;
                while ((strLine = reader.readLine()) != null) {
                    sb.append(strLine);
                }
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(out, reader);
            closeConnection(connection);
        }
        return "";
    }

    public static void close(Closeable... args) {
        for (Closeable closeable : args) {
            if (closeable != null) {
                try {
                    closeable.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static void closeConnection(HttpURLConnection connection) {
        if (connection != null) {
            connection.disconnect();
        }
    }

    public static void main(String[] args) {
        byte[] data = downloadFile(
            "https://4f7fce38e855e98a0d722672fc0a4ef4.dlied1.cdntips.net/dl.softmgr.qq.com/original/Picture/FocusOnIV64_1.23.exe?mkey=607322a66f1278d3 &f=9870 &cip=111.1 8.94.38& amp;proto=https",
            "C:\Users\\admin\Desktop", "FocusOnIV64_1.23.exe");
        Map<String, String> textMap = new HashMap<String, String>();
        textMap.put("id", "123");
        textMap.put("name", "zinredible");
        String responseStr =
            uploadFile("http://127.0.0.1/api/his/upload", textMap, "testFile", data, "FocusOnIV64_1.23.exe");
        System.out.println(responseStr);
    }
}
// springboot interface
@PostMapping(value = "/api/his/upload", produces = "multipart/form-data;charset=UTF-8")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", paramType = "form"),
        @ApiImplicitParam(name = "name", paramType = "form")})
    public String uploadFile(TestParam param, MultipartFile testFile,HttpServletRequest request) throws Exception