Post Java back end with File documents and other parameters of the request

Post Java and other files with File parameters for file upload request, the client is usually the page, implemented in front-end web pages upload files is not difficult to write a form, add enctype = "multipart / form-data", in writing received on it, not that hard. If you want java.net.HttpURLConnection, java background to achieve file upload, really engage in a little head, ideas and specific steps to achieve the request is to simulate the page, the page format issued as follows: ----------- ------------------ 7da2e536604c8 Content-Disposition: form-data; name = "luid" 123 ----------------- ------------ 7da2e536604c8 Content-Disposition: form-data; name = "file1"; filename = "D: \ haha.txt" Content-Type: text / plain haha ​​hahaha ---- ------------------------- 7da2e536604c8 Content-Disposition: form-data; name = "file"; filename = "D: \ huhu.png" Content-Type: application / octet-stream here is a picture of binary data ----------------------------- 7da2e536604c8-

demo code only two parameters, a File, a String ---------------- Disclaimer: This article is the original article CSDN bloggers "jianbin.huang", and follow CC 4.0 by- sa copyright agreement, reproduced, please attach the original source link and this statement. Original link: https: //blog.csdn.net/qq_17782389/article/details/91519554

 

public static void sendPostWithFile(String filePath) {
        DataOutputStream out = null;
        final String newLine = "\r\n";
        final String prefix = "--";
        try {
            URL url = new URL("https://ws-di1.sit.cmrh.com/aiisp/v1/mixedInvoiceFileOCR");
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();

            String BOUNDARY = "-------7da2e536604c8";
            conn.setRequestMethod("POST");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

            out = new DataOutputStream(conn.getOutputStream());

            File (filePath);new new
            File File =add parameters File//
            the StringBuilder SB1= new StringBuilder();
            sb1.append(prefix);
            sb1.append(BOUNDARY);
            sb1.append(newLine);
            sb1.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"" + newLine);
            sb1.append("Content-Type:application/octet-stream");
            sb1.append(newLine);
            sb1.append(newLine);
            out.write(sb1.toString().getBytes());
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            byte[] bufferOut = new byte[1024];
            int bytes = 0;
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            out.write(newLine.getBytes());
            in.close();

            // 添加参数sysName
            StringBuilder sb = new StringBuilder();
            sb.append(prefix);
            sb.append(BOUNDARY);
            sb.append(newLine);
            sb.append("Content-Disposition: form-data;name=\"sysName\"");
            sb.append(newLine);
            sb.append(newLine);
            sb.append("test");
            out.write(sb.toString().getBytes());
            
             // 添加参数returnImage
            StringBuilder sb2 = new StringBuilder();
            sb2.append(newLine);
            sb2.append(prefix);
            sb2.append(BOUNDARY);
            sb2.append(newLine);
            sb2.append("Content-Disposition: form-data;name=\"returnImage\"");
            sb2.append(newLine);
            sb2.append(newLine);
            sb2.append("false");
            out.write(sb2.toString().getBytes());

            byte[] = End_data ( "\ R & lt \ N--" the BOUNDARY + + "- \ R & lt \ n-" ) .getBytes ();
             // write end identification 
            out.write (end_data); 
            out.flush (); 
            OUT .close (); 

            // define BufferedReader input stream in response to read the URL 
            BufferedReader Reader = new new BufferedReader ( new new the InputStreamReader (conn.getInputStream ())); 
            String Line = null ;
             the while ((Line = reader.readLine ()) ! = null ) { 
                System.out.println (Line); 
            } 

        } the catch(Exception E) { 
            System.out.println ( "POST request transmission abnormality!" + E); 
            e.printStackTrace (); 
        } 
    } 
 --------
/**
 * post请求 不带file
 * 参数使用
 * JSONObject jp = new JSONObject();
 *  String param = jp.toJSONString()
 */
 public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // URL realUrl = new URL("https://testzoms.txffp.com/pcs/app/common/checkInvoice");
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            define BufferedReader input stream to read the URL of the response//
            = in new new the BufferedReader ( new new the InputStreamReader (conn.getInputStream ())); 
            String Line; 
            the while (! (= in.readLine Line ()) = null ) { 
                Result + = Line;
                 // System.out.println (Result) ; 
            } 
        } the catch (exception E) { 
            System.out.println ( "! sending a POST abnormal" + E); 
            e.printStackTrace (); 
        } 
        // use the finally block to close the output stream, the input stream 
        finally {
             the try {
                 if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
/**
     * post请求 带file,map是其余参数
     */
     
    public static JSONObject sendPostWithFile(MultipartFile file, HashMap<String, Object> map) {
        DataOutputStream out = null;
        DataInputStream in = null;
        final String newLine = "\r\n";
        final String prefix = "--";
        JSONObject json = null;
        PropUtils propUtils = new PropUtils("cfg.properties");
        try {
            String fileOCRUrl = propUtils.getProp("fileOCRUrl");
            URL url = new URL(fileOCRUrl);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();

            String BOUNDARY = "-------KingKe0520a";
            conn.setRequestMethod("POST");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            out = new DataOutputStream(conn.getOutputStream());

            // 添加参数file
            // File file = new File(filePath);
            StringBuilder sb1 = new StringBuilder();
            sb1.append(prefix);
            sb1.append(BOUNDARY);
            sb1.append(newLine);
            sb1.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"" + newLine);
            sb1.append("Content-Type:application/octet-stream");
            sb1.append(newLine);
            sb1.append(newLine);
            out.write(sb1.toString().getBytes());
            // in = new DataInputStream(new FileInputStream(file));
            in = new DataInputStream(file.getInputStream());
            byte[] bufferOut = new byte[1024];
            int bytes = 0;
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            out.write(newLine.getBytes());

            StringBuilder sb = new StringBuilder();
            int k = 1;
            for (String key : map.keySet()) {
                if (k != 1) {
                    sb.append(newLine);
                }
                sb.append(prefix);
                sb.append(BOUNDARY);
                sb.append(newLine);
                sb.append("Content-Disposition: form-data;name=" + key + "");
                sb.append(newLine);
                sb.append(newLine);
                sb.append(map.get(key));
                out.write(sb.toString().getBytes());
                sb.delete(0, sb.length());
                k++;
            }

            // 添加参数sysName
            /*StringBuilder sb = new StringBuilder();
            sb.append(prefix);
            sb.append(BOUNDARY);
            sb.append(newLine);
            sb.append("Content-Disposition: form-data;name=\"sysName\"");
            sb.append(newLine);
            sb.append(newLine);
            sb.append("test");
            out.write(sb.toString().getBytes());*/

            // 添加参数returnImage
            /*StringBuilder sb2 = new StringBuilder();
            sb2.append(newLine);
            sb2.append(prefix);
            sb2.append(BOUNDARY);
            sb2.append(newLine);
            sb2.append("Content-Disposition: form-data;name=\"returnImage\"");
            sb2.append(newLine);
            sb2.append(newLine);
            sb2.append("false");
            out.write(sb2.toString().getBytes());*/

            byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            out.write(end_data);
            out.flush();

            new new
            BufferedReader Reader =define BufferedReader input stream to retrieve the response of the URL// BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            StringBuffer resultStr = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                resultStr.append(line);
            }
            json = (JSONObject)JSONObject.parse(resultStr.toString());

    } catch (Exception e) {
        System.out.println("发送POST请求出现异常!" + e);
        e.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
        return json;
    }
 
/ ** 
 * profile generic class 
 * Usage: instantiated directly call getprop () 
 * new new PropUtils (filePath) incoming file paths, resources following partial path 
 * @author Jianbin
  * / 
public  class PropUtils {
     Private the Properties Properties; 
    
    public PropUtils (String propertisFile) { 
        the InputStream in = null ;
         the try { 
            Properties = new new the Properties (); 
            in = PropUtils. class .getResourceAsStream ( "/" + propertisFile); 
            Properties.load (in); 
        } the catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public String getProp(String key){
        return properties.getProperty(key);
    }
    
    /*public static void main(String[] args) {
        PropUtils propUtils = new PropUtils("cfg.properties");
        String str = propUtils.getProp("jobStatus.3");
        System.out.println(str);
    }*/
    
}
 

 

Guess you like

Origin www.cnblogs.com/kaschie/p/11423195.html