后台提交MultipartFile模拟form表单

后台提交MultipartFile模拟form表单

 public static String doPostWithFile(String url, MultipartFile file) {
        String result = "";
        try {
            // 数据分隔线
            String BOUNDARY = "-----------"+System.currentTimeMillis();
            
            URL realurl = new URL(url);
            // 发送POST请求设置头部信息
            HttpURLConnection connection = (HttpURLConnection) realurl.openConnection();
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(30000);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection","Keep-Alive");
            connection.setRequestProperty("User-Agent",
                            "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0");
            connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);

            // 内容
            StringBuffer contentBody =new StringBuffer("--"+BOUNDARY);
            // 尾
            String endBoundary ="\r\n--" + BOUNDARY + "--\r\n";

            OutputStream out = new DataOutputStream(connection.getOutputStream());

            contentBody.append("\r\n")
                    .append("Content-Disposition:form-data;name=\"fileObj\";filename=\"")
                    .append(file.getOriginalFilename()).append("\"")
                    .append("\r\n")
                    .append("Content-Type:image/jpeg")
                    .append("\r\n\r\n");
            String boundaryMessage2 = contentBody.toString();
            System.out.println(boundaryMessage2);

            out.write(boundaryMessage2.getBytes("utf-8"));

            // 写文件
            DataInputStream dis= new DataInputStream(file.getInputStream());
            int bytes = 0;
            byte[] bufferOut =new byte[(int) file.getSize()];
            bytes =dis.read(bufferOut);
            out.write(bufferOut,0, bytes);
            dis.close();

            out.write(endBoundary.getBytes("utf-8"));
            out.flush();
            out.close();

            // 从服务器获得回答
            String strLine="";
            String strResponse ="";
            InputStream in =connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            while((strLine =reader.readLine()) != null)
            {
                strResponse +=strLine +"\n";
            }
            System.out.println("从服务器获得的回答:");
            System.out.print(strResponse);
            return strResponse;
        } catch (Exception e) {
            System.out.println("发送POST请求出现异常!" + e);
            e.printStackTrace();
        }
        return result;
    }

你可能感兴趣的:(springboot)