• Java模拟表单post提交,可支持图片上传


    /**
    * 模拟表单post
    *
    * @param textMap 文本域
    * @param fileMap 文件
    *
    */

    public static String postForm(String urlStr, Map<String, String> textMap, Map<String, String> fileMap) throws IOException {
        String res = "";
        HttpURLConnection conn = null;
        InputStream inS = null;
        OutputStream out = null;
        String BOUNDARY = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            if (conn instanceof HttpsURLConnection) {
                ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory);
                ((HttpsURLConnection) conn).setHostnameVerifier(trustAnyHostnameVerifier);
            }
    
            conn.setConnectTimeout(19000);
            conn.setReadTimeout(19000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
    
            out = new DataOutputStream(conn.getOutputStream());
            // text value
            if (textMap != null) {
                StringBuffer strBuf = new StringBuffer();
                Iterator iter = textMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    String inputName = (String) entry.getKey();
                    String inputValue = (String) entry.getValue();
                    if (inputValue == null) {
                        continue;
                    }
                    strBuf.append("
    ").append("--").append(BOUNDARY).append("
    ");
                    strBuf.append("Content-Disposition: form-data; name="" + inputName + ""
    
    ");
                    strBuf.append(inputValue);
                }
                out.write(strBuf.toString().getBytes());
            }
    
            // file
            if (fileMap != null) {
                Iterator iter = fileMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    String inputName = (String) entry.getKey();
                    String inputValue = (String) entry.getValue();
                    if (inputValue == null) {
                        continue;
                    }
                    File file = new File(inputValue);
                    String filename = file.getName();
                    String contentType = new MimetypesFileTypeMap().getContentType(file);
                    if (filename.endsWith(".png")) {
                        contentType = "image/png";
                    } else if (filename.endsWith(".gif")) {
                        contentType = "image/gif";
                    } else if (filename.endsWith(".jpg")) {
                        contentType = "image/jpeg";
                    }
                    if (contentType == null || contentType.equals("")) {
                        contentType = "application/octet-stream";
                    }
    
                    StringBuffer strBuf = new StringBuffer();
                    strBuf.append("
    ").append("--").append(BOUNDARY).append("
    ");
                    strBuf.append("Content-Disposition: form-data; name="" + inputName + ""; filename="" + filename + ""
    ");
                    strBuf.append("Content-Type:" + contentType + "
    
    ");
    
                    out.write(strBuf.toString().getBytes());
    
                    DataInputStream 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);
                    }
                }
            }
    
            byte[] endData = ("
    --" + BOUNDARY + "--
    ").getBytes();
            out.write(endData);
            out.flush();
    
            // 读取返回数据
            StringBuffer strBuf = new StringBuffer();
            inS = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inS));
            String line = null;
            while ((line = reader.readLine()) != null) {
                strBuf.append(line).append("
    ");
            }
            res = strBuf.toString();
            reader.close();
            reader = null;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
            if (inS != null) {
                inS.close();
            }
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
        return res;
    }
  • 相关阅读:
    web应用/http协议/web框架
    算法-排序-1.冒泡排序/2.选择排序/3.插入排序
    算法-基础和查找-1.汉诺塔/2.顺序查找/3.二分查找/4.顺序查找和二分查找的比较
    前端开发
    前端开发
    前端开发
    前端开发
    数据库
    LeetCode : Add Binary
    LeetCode : Length of Last Word
  • 原文地址:https://www.cnblogs.com/xiuxiu123/p/5130797.html
Copyright © 2020-2023  润新知