前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >Java模拟表单post提交,可支持图片上传

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

原创
作者头像
用户1503405
修改2021-09-24 10:12:01
修改2021-09-24 10:12:01
1.3K00
代码可运行
举报
文章被收录于专栏:棒棒小飞人棒棒小飞人
运行总次数:0
代码可运行
代码语言:javascript
代码运行次数:0
运行
复制
/**

 * 模拟表单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("\r\n").append("--").append(BOUNDARY).append("\r\n");
                strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
                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("\r\n").append("--").append(BOUNDARY).append("\r\n");
                strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");
                strBuf.append("Content-Type:" + contentType + "\r\n\r\n");

                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 = ("\r\n--" + BOUNDARY + "--\r\n").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;
}</pre> 

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档