• httpurlconnection模拟post提交form表单(普通文本和上传文件) (


    http://blog.sina.com.cn/s/blog_8417657f0101gvpc.html

    用HttpUrlConnection模拟post表单进行文件上传平时很少使用,比较麻烦。

    原理是: 分析文件上传的数据格式,然后根据格式构造相应的发送给服务器的字符串。

    格式如下:这里的httppost123是我自己构造的字符串,可以是其他任何的字符串

    ----------httppost123 ( )
    Content-Disposition: form-data; name="img"; filename="t.txt" ( )
    Content-Type: application/octet-stream ( )

    ( )

    sdfsdfsdfsdfsdf ( )
    ----------httppost123 ( )
    Content-Disposition: form-data; name="text" ( )

    ( )

    text tttt ( )
    ----------httppost123-- ( )
    ( )

    上面的( )表示各个数据必须以( )结尾。

    package com.haitai.IntelligentAdapters.common;
    import java.io.ByteArrayOutputStream; 
    import java.io.DataInputStream; 
    import java.io.File; 
    import java.io.FileInputStream; 
    import java.io.InputStream; 
    import java.io.OutputStream; 
    import java.util.ArrayList; 
    import java.util.List; 
    import java.net.HttpURLConnection; 
    import java.net.URL;


    public class HttpMultipartRequest {

         //每个post参数之间的分隔 
        static final String BOUNDARY = "----MyFormBoundarySMFEtUYQG6r5B920";  // 定义数据分隔线  
        private String urlStr;  // 连接的地址
        private List<String[]> strParams; // 文字post项集 strParams 1:key 2:value  
        private List<String[]> fileParams; // 文件的post项集 fileParams 1:fileField, 2.fileName, 3.fileType, 4.filePath  
     
      
         
        public HttpMultipartRequest(String urlStr, List<String[]> strParams, List<String[]> fileParams) { 
            this.urlStr = urlStr; 
            this.strParams = strParams; 
            this.fileParams = fileParams; 
     
        } 
     
         
        public byte[] sendPost() throws Exception {    
            HttpURLConnection hc = null;  //http连接器
            ByteArrayOutputStream bos = null;//byte输出流,用来读取服务器返回的信息   
            InputStream is = null;//输入流,用来读取服务器返回的信息  
            byte[] res = null;//保存服务器返回的信息的byte数组
            try { 
                URL url = new URL(urlStr); 
                hc = (HttpURLConnection) url.openConnection(); 
     
                hc.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); 
                hc.setRequestProperty("Charsert", "UTF-8"); 
                // 发送POST请求必须设置如下两行 
                hc.setDoOutput(true); 
                hc.setDoInput(true); 
                hc.setUseCaches(false); 
                hc.setRequestMethod("POST"); 
     
                OutputStream dout = hc.getOutputStream(); 
                ////1.先写文字形式的post流 
                //头 
                String boundary = BOUNDARY; 
                //中 
                StringBuffer resSB = new StringBuffer(" "); 
                //尾 
                String endBoundary = " --" + boundary + "-- "; 
                //strParams 1:key 2:value 
                if(strParams != null){ 
                    for(String[] parsm : strParams){ 
                        String key = parsm[0]; 
                        String value = parsm[1]; 
                        resSB.append("Content-Disposition: form-data; name="").append(key).append("" ").append(" ").append(value).append(" ").append("--").append(boundary).append(" "); 
                    } 
                } 
                String boundaryMessage = resSB.toString(); 
                 
                //写出流 
                dout.write( ("--"+boundary+boundaryMessage).getBytes("utf-8") ); 
                 
                //2.再写文件开式的post流 
                //fileParams 1:fileField, 2.fileName, 3.fileType, 4.filePath 
                resSB = new StringBuffer(); 
                if(fileParams != null){ 
                    for(int i=0, num=fileParams.size(); i<num; i++){ 
                        String[] parsm = fileParams.get(i); 
                        String fileField = parsm[0]; 
                        String fileName = parsm[1]; 
                        String fileType = parsm[2]; 
                        String filePath = parsm[3]; 
                         
                        resSB.append("Content-Disposition: form-data; name="").append(fileField).append(""; filename="").append( 
                                fileName).append("" ").append("Content-Type: ").append(fileType).append(" "); 
                         
                        dout.write( resSB.toString().getBytes("utf-8") ); 
                         
                        //开始写文件 
                        File file = new File(filePath); 
                        DataInputStream in = new DataInputStream(new FileInputStream(file)); 
                        int bytes = 0; 
                        byte[] bufferOut = new byte[1024 * 5]; 
                        while ((bytes = in.read(bufferOut)) != -1) { 
                            dout.write(bufferOut, 0, bytes); 
                        } 
                         
                        if(i<num-1){ 
                            dout.write( endBoundary.getBytes("utf-8") ); 
                        } 
                         
                        in.close(); 
                    } 
                     
                } 
                 
                //3.最后写结尾 
                dout.write( endBoundary.getBytes("utf-8") );    
                dout.close();  

                int ch;  
                is = hc.getInputStream();    
                bos = new ByteArrayOutputStream(); 
                while ((ch = is.read()) != -1) { 
                    bos.write(ch); 
                } 
                res = bos.toByteArray(); 
            } catch (Exception e) { 
                e.printStackTrace(); 
            } finally { 
                try { 
                    if (bos != null) 
                        bos.close();  
                    if (is != null) 
                        is.close();  
                } catch (Exception e2) { 
                    e2.printStackTrace(); 
                } 
            } 
            return res; 
        }  
      
      

    }

  • 相关阅读:
    UI、JS框架----Bootstrap、Metro
    重构—改善既有代码的设计4——构筑测试体系
    重构—改善既有代码的设计3——代码的坏味道
    正则匹配-URL-域名
    pgAdmin的数据恢复
    重构—改善既有代码的设计2
    重构—改善既有代码的设计1
    Levenshtein Distance,判断字符串的相似性
    最大匹配字符串LCS,The Longest Common Substring
    email
  • 原文地址:https://www.cnblogs.com/jiezzy/p/3727443.html
Copyright © 2020-2023  润新知