java模拟from表单提交,上传图片

/**
     * java上传表单,有图片
     * @param urlStr     上传地址
     * @param textMap    表单参数
     * @param fileMap    文件参数 key:文件名称   value:文件地址
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static String formUpload(String urlStr, Map<String, String> textMap,
                                    Map<String, String> fileMap) {
        String res = "";
        HttpURLConnection conn = null;
        // boundary就是request头和上传文件内容的分隔符
        String BOUNDARY = "---------------------------123821742118716";
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            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);
            OutputStream out = new DataOutputStream(conn.getOutputStream());
            // text
            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();

                    //没有传入文件类型,同时根据文件获取不到类型,默认采用application/octet-stream
                    String contentType = new MimetypesFileTypeMap().getContentType(file);
                    //contentType非空采用filename匹配默认的图片类型
                    if(!"".equals(contentType)){
                        if (filename.endsWith(".png")) {
                            contentType = "image/png";
                        }else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {
                            contentType = "image/jpeg";
                        }else if (filename.endsWith(".gif")) {
                            contentType = "image/gif";
                        }else if (filename.endsWith(".ico")) {
                            contentType = "image/image/x-icon";
                        }
                    }
                    if (contentType == null || "".equals(contentType)) {
                        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);
                    }
                    in.close();
                }
            }
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            out.write(endData);
            out.flush();
            out.close();
            // 读取返回数据
            StringBuffer strBuf = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                strBuf.append(line).append("\n");
            }
            res = strBuf.toString();
            reader.close();
            reader = null;
        } catch (Exception e) {
            System.out.println("发送POST请求出错。" + urlStr);
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
        return res;
    }

原文地址:https://www.cnblogs.com/chenziyu/p/9706107.html

时间: 2024-08-01 22:46:53

java模拟from表单提交,上传图片的相关文章

Java模拟POST表单提交HttpClient操作

public static void Login() { String url = "http://www.***.com/login"; PostMethod postMethod = new PostMethod(url); // 填入各个表单域的值 NameValuePair[] data = { new NameValuePair("account", "[email protected]"), new NameValuePair(&qu

通过HttpURLConnection模拟post表单提交

package junit; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import org.junit.Test; import com.hrtx.util.StreamTool; public class EsmTest { /** * 通过HttpURLConnection模拟post表单提交 * @throws Exception */ @Test public

Linux curl 模拟form表单提交信息和文件

curl是一个命令行方式下传输数据的开源传输工具,支持多种协议:FTP.HTTP.HTTPS.IMAP.POP3.TELNET等,功能超级强大. 我今天想说的是程序开发中常用的模拟Form提交 1.GET提交 特别简单直接写url里面 2.POST提交    通过 --data/-d 方式指定使用POST方式传递数据 3.模拟form表单提交文件  --form/-F 模拟form表单提交文件 这个命令超级好用,再也不用为了写上传接口,而被迫写一个Form表单了 "[email protecte

HTML5第8次课堂笔记( 模拟form表单提交数据,xml的解析,jQuery的Ajax方法使用, mui的ajax)

HTML5第8次课堂笔记 1.  模拟form表单提交数据:(get方式) <body> <formmethod="get"action="DataTest7"> <inputtype="text"name="uname"value="yang"id="myname"><br/> <inputtype="password&q

js模拟form表单提交数据, js模拟a标签点击跳转,避开使用window.open引起来的浏览器阻止问题

js模拟form表单提交数据源码: /** * js模拟form表单提交 * @param {object} 参数对象 * url 必填 提交地址 * methond 选填 默认post 提交方式 post get * target 选填 默认_self 当前页面还是新页面 _self _blank * 其它参数 */ function jsFormSubmit(params) { var turnForm = document.createElement("form"); //一定要

php 利用http上传协议(表单提交上传图片 )

主要就是利用php 的 fsocketopen 消息传输. 这里先通过upload.html 文件提交,利用chrome抓包,可以看到几个关键的信息. 首先指定了表单类型为multipart/form-data;. boundary是分隔符 因为上传文件不在使用原有的http协议了.请求内容不再可能以 x = y方式发送了.而使用了 分隔符 字段内容 分隔符号 字段内容2 而boundary就是指定分隔符号的标志. 请求的内容就应该是这样的了. 在来看下消息体 #socket_upload.ph

Fiddler 模拟form表单提交

Fiddler 是开发人员神器,大家都见识了 今天用 Fiddler 模拟form提交,http返回状态倒是200,就是死活得不到正确的返回结果 如图: 解决方法:Content-Type: application/x-www-form-urlencoded

MVC3下异步表单提交上传图片实现

由于项目需要[任何一个人都能上传不定张图片],这两天就在写这个功能.现在写完了,记录下. 语言:C# 环境:MVC3 + EF4 所需插件下载地址:http://download.csdn.net/detail/tl110110tl/8248099 所需数据库表如下图: 插件参考:http://www.cnblogs.com/china-li/archive/2012/12/12/2800144.html html代码: @{ Layout = null; } <!DOCTYPE html>

Ajax模拟Form表单提交,含多种数据上传

<div> <table id="outputInfo"> <tr><td>Client</td><td><input id='ClientName' type='text'></td></tr> <tr><td>CropID</td><td><input id='CropID' type='text' /></t