加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 03:14:08 所属栏目:Java 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 /** * 模拟表单post * * @param textMap 文本域 * @param fileMap 文件 * */ public static String postForm(String urlStr,MapString,String textMap

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

/**
     * 模拟表单post
     *
     * @param textMap 文本域
     * @param fileMap 文件
     *
     */
    public static String postForm(String urlStr,Map<String,String> textMap,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("rn").append("--").append(BOUNDARY).append("rn");
                    strBuf.append("Content-Disposition: form-data; name="" + inputName + ""rnrn");
                    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("rn").append("--").append(BOUNDARY).append("rn");
                    strBuf.append("Content-Disposition: form-data; name="" + inputName + ""; filename="" + filename + ""rn");
                    strBuf.append("Content-Type:" + contentType + "rnrn");
 
                    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,bytes);
                    }
                }
            }
 
            byte[] endData = ("rn--" + BOUNDARY + "--rn").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("n");
            }
            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;
    }

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读