利用HttpClient发送基于Content-Type="multipart/form-data"形式的表单

来源:互联网 发布:淘宝抱枕推荐 编辑:程序博客网 时间:2024/05/21 03:57

一、利用HttpClient发送基于Content-Type="multipart/form-data"形式的表单

package com.test.httpclient;import java.io.IOException;import java.util.Map;import javax.servlet.ServletException;import org.apache.commons.httpclient.methods.RequestEntity;import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;import org.apache.commons.httpclient.methods.multipart.Part;import org.apache.commons.httpclient.methods.multipart.StringPart;import org.apache.commons.httpclient.methods.PostMethod;import org.apache.commons.httpclient.params.HttpMethodParams;import org.apache.commons.httpclient.HttpClient;publicclass SendXmlAction{    public String execute() throws ServletException, IOException    {        String xmlhead = this.getRequest().getParameter("xmlhead");        String xmlbody = this.getRequest().getParameter("xmlbody");        System.out.println("xmlhead == "+xmlhead);        System.out.println("xmlbody == "+xmlbody);                // 用远程服务的URL设置生成POST方法,供HTTP客户端执行        String remoteUrl = "http://**.**.***.***:8888/project/receiveServlet";                PostMethod method = new PostMethod(remoteUrl);                // multipart/form-data; boundary=---------------------------7de2b13a790640                //method.addParameter("xmlhead", xmlhead);        //method.addParameter("xmlbody", xmlbody);                HttpClient HTTP_CLINET = new HttpClient();                synchronized (HTTP_CLINET)        {            try            {                //使用多重发送方式,发送两个独立的两个XML Part,基于Content-Type="multipart/form-data"形式的表单                Part[] parts = {new StringPart("xmlhead",xmlhead), new StringPart("xmlbody",xmlbody)}; //StringPart和FilePart都可以放进去                RequestEntity requestEntity = new MultipartRequestEntity(parts, method.getParams());                method.setRequestEntity(requestEntity);                                method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 30000);                //链接超时 30秒                HTTP_CLINET.getHttpConnectionManager().getParams().setConnectionTimeout(30000);                //读取超时 30秒                HTTP_CLINET.getHttpConnectionManager().getParams().setSoTimeout(30000);                                HTTP_CLINET.executeMethod(method);                                String[] result = new String[2];                result[0] = String.valueOf(method.getStatusCode());                result[1] = method.getResponseBodyAsString();                System.out.println("http status : "+result[0]);                System.out.println("http response : "+result[1]);                            }            catch (Exception e)            {                e.printStackTrace();            }            finally            {                if (method != null)                {                    method.releaseConnection();                }                method = null;            }        }                return "success";    }}

 

二、MultipartRequest接收参数

package com.test.servlet;import java.io.IOException;import java.io.PrintWriter;import java.io.File;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.log4j.Logger;import com.oreilly.servlet.MultipartRequest;publicclass BossServlet extends HttpServlet{    /** serialVersionUID */private Logger logger = Logger.getLogger(BossServlet.class);    publicvoid doGet(HttpServletRequest request, HttpServletResponse response)            throws IOException, ServletException    {        this.doPost(request, response);    }    protectedvoid doPost(HttpServletRequest request,            HttpServletResponse response) throws ServletException, IOException    {                // MultipartRequest        String head = null ;        String body = null ;                try        {            File fileDir = new File(this.getServletContext().getRealPath("/formhttp"));            if (!fileDir.exists())            {                fileDir.mkdirs();            }                        int inmaxPostSize = 10 * 1024 * 1024;                        // utf-8中文编码模式上传文件            MultipartRequest multirequest = new MultipartRequest(request,fileDir.getAbsolutePath(),inmaxPostSize,"UTF-8");                         head = multirequest.getParameter("head");            body = multirequest.getParameter("body");            System.out.println("xmlHead2 = " + xmlHead);            System.out.println("xmlBody2 = " + xmlBody);        }        catch (Exception e)        {            e.printStackTrace();        }        response.setCharacterEncoding("UTF-8");        response.setContentType("multipart/mixed;boundary=---------------------------7de2b13a790640");         PrintWriter out = response.getWriter();        String res = null;        try        {            res = .....        }        catch (Exception e)        {            e.printStackTrace();        }        if (!(res == null || "".equals(res)))        {            try            {                out.println(res);            }            catch (Exception e)            {                e.printStackTrace();            }            finally            {                out.close();            }        }    }    publicvoid init() throws ServletException    {        super.init();    }}

 若发送基于Content-Type="multipart/form-data"形式的表单,却通过request.getParameter("**")获取参数值,则获取的参数值为空。

阅读全文
0 0
原创粉丝点击