java后端模拟表单提交

代码可实现文本域及非文本域的处理

请求代码:

/**
     * 上传
     *
     * @param urlStr
     * @param textMap
     * @param fileMap
     * @return
     */
    public static String formUpload(String urlStr, Map<String, String> textMap,
            Map<String, String> fileMap) {
        String res = "";
        HttpURLConnection conn = null;
        String BOUNDARY = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符
        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();
                    String contentType = new MimetypesFileTypeMap()
                            .getContentType(file);
                    if (filename.endsWith(".png")) {
                        contentType = "image/png";
                    }
                    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);
                    }
                    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;
    }

  处理上传请求代码:

/**
	 * 上传
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	public void doUpload(HttpServletRequest request, HttpServletResponse response)throws Exception {
		String jsession = request.getParameter("jsessionid");
		System.out.println(jsession);
		HttpSession s = request.getSession();
		System.out.println(s.getId());
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 设置内存缓冲区,超过后写入临时文件
		factory.setSizeThreshold(10240000);
		ServletFileUpload upload = new ServletFileUpload(factory);
		// 设置单个文件的最大上传值
		upload.setFileSizeMax(10002400000l);
		// 设置整个request的最大值
		upload.setSizeMax(10002400000l);
		upload.setHeaderEncoding("UTF-8");
		//Date now = new Date();
		Map map = new HashMap();
		File tmpFile = new File(tmpFilePath);
		if(!tmpFile.exists())
			tmpFile.mkdirs();
		List items = null;
		try {
			items = upload.parseRequest(request);
		} catch (FileUploadException e) {
			throw new RuntimeException(e);
		}
		if (items == null)
			return ;
		Date date = new Date();
		Iterator iter = items.iterator();

		String fileName = tmpFilePath + File.separator +date.getTime();

		while (iter.hasNext()) {// 循环获得每个表单项
			FileItem item = (FileItem) iter.next();
			if (item.isFormField()) {
				String name = item.getFieldName();
				try {
					String value = item.getString("utf-8");// 如果参数里面有中文,防止出现乱码
					map.put(name, value);
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else if(item.getName().length() > 0) {
				String namefix = item.getName();
				namefix = namefix.substring(namefix.lastIndexOf("."));
				fileName = fileName +namefix;
				item.write(new File(fileName));
			}

		}
		String type =(String) map.get("type");
		if(type.equals("war")){
			request.getSession().setAttribute("warFileName",fileName);
		}else if(type.equals("sql")){
			request.getSession().setAttribute("sqlFileName",fileName);
		}
		try {
			map.put("data", fileName);
			response.getWriter().write(JsonUtils.convertToString(map));
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

  测试调用代码:

/**
     * @param args
     */
    public static void main(String[] args) {  

        String filepath="D:\\test\\PPGhost.war";  

        String urlStr = "http://localhost:8080/iopm/version/add.do?method=upload";  

        Map<String, String> textMap = new HashMap<String, String>();  

        textMap.put("name", "testname");
        textMap.put("type", "war");  

        Map<String, String> fileMap = new HashMap<String, String>();  

        fileMap.put("userfile", filepath);  

        String ret = formUpload(urlStr, textMap, fileMap);  

        System.out.println(ret);  

    }

  

时间: 2024-08-01 01:37:12

java后端模拟表单提交的相关文章

HTTP通信模拟表单提交数据

前面记录过一篇关于http通信,发送数据的文章:http://www.cnblogs.com/hyyq/p/7089040.html,今天要记录的是如何通过http模拟表单提交数据. 一.通过GET请求方式提交:最简单的一种方式 直接在链接后面跟上要提交的数据即可,比如: http://yychf.55555.io/get.do?username=yyc&password=yychf,通过http直接发送.然后在服务器端可以通过request.getParameter()方法来获得参数值.如要获

表单提交---前端页面模拟表单提交(form)

有些时候我们的前端页面总没有<form></form>表单,但是具体的业务时,我们又必须用表单提交才能达到我们想要的结果,LZ最近做了一些关于导出的一些功能,需要调用浏览器默认的下载功能,如果用ajax请求,则无法调用.所以只能用表单提交的方式请求后台方可调用浏览器默认的下载功能.这个时候我们只能自己手动添加<form></form>元素.这里LZ提供我自己遇到的两种情况: 一:在原有的html结构包上<form></form>标签,

C# Winform利用POST传值方式模拟表单提交数据(Winform与网页交互)

其原理是,利用winfrom模拟表单提交数据,将要提交的参数提交给网页,网页执行代码,得到数据,然后Winform程序将网页的所有源代码读取下来,这样就达到windows应用程序和web应用程序之间传参和现实数据的效果了. - 首先创建一个windows应用程序和web应用程序. - 在web应用程序中,将网页切换到源代码并把源代码中一些没用的代码删掉,只保留头部,在windows应用程序读取网页源码时,这些都会被一起读下来,但这些都是没用的数据,而且删掉没什么影响.需要保留的代码如下: - <

&lt;记录&gt; axios 模拟表单提交数据

ajax 可以通过 FormData 对象模拟表单提交数据 第一种方式:自定义FormData信息 //创建formData对象 var formData = new FormData(); //添加键值对 formData.append("team_id", this.team_id) formData.append("content", this.content) formData.append("img", this.img) formDa

c# 模拟表单提交,post form 上传文件、大数据内容

表单提交协议规定:要先将 HTTP 要求的 Content-Type 设为 multipart/form-data,而且要设定一个 boundary 参数,这个参数是由应用程序自行产生,它会用来识别每一份资料的边界 (boundary),用以产生多重信息部份 (message part).而 HTTP 服务器可以抓取 HTTP POST 的信息, 基本内容:1. 每个信息部份都要用 --[BOUNDARY_NAME] 来包装,以分隔出信息的每个部份,而最后要再加上一个 --[BOUNDARY_N

利用HttpWebRequest模拟表单提交

1 using System; 2 using System.Collections.Specialized; 3 using System.IO; 4 using System.Net; 5 using System.Text; 6 7 namespace Allyn.Common 8 { 9 public class HttpHelper 10 { 11 /// <summary> 12 /// 获取指定路径数据 13 /// </summary> 14 /// <par

Java利用Http模拟表单提交

private static String sendPost(String url, NameValuePair[] params) { HttpClient client = new HttpClient(); // 请求超时 client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000); // 读取超时 client.getParams().setParameter(CoreConnection

真理胜于一切 JAVA模拟表单提交

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; public class HttpRequest { /** *

ajax模拟表单提交,后台使用npoi实现导入操作 方式一

页面代码: <form id="form1" enctype="multipart/form-data"> <div style="float:right">   <button type="button" class="btn btn-primary" onclick="$('#fileUpload').click()" id="reviewFi