HttpClient sending Multipart/form-data type parameters and receiving parameters with Multipartrequest

Source: Internet
Author: User

I. Using httpclient to send forms based on content-type= "Multipart/form-data"

 Packagecom.test.httpclient;Importjava.io.IOException;ImportJava.util.Map;Importjavax.servlet.ServletException;Importorg.apache.commons.httpclient.methods.RequestEntity;Importorg.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;ImportOrg.apache.commons.httpclient.methods.multipart.Part;ImportOrg.apache.commons.httpclient.methods.multipart.StringPart;ImportOrg.apache.commons.httpclient.methods.PostMethod;ImportOrg.apache.commons.httpclient.params.HttpMethodParams;Importorg.apache.commons.httpclient.HttpClient; Public classsendxmlaction{ PublicString Execute ()throwsservletexception, IOException {String xmlhead= This. Getrequest (). GetParameter ("Xmlhead"); String Xmlbody= This. Getrequest (). GetParameter ("Xmlbody"); System.out.println ("Xmlhead = =" +xmlhead); System.out.println ("Xmlbody = =" +xmlbody); //generate the Post method with the URL settings of the remote service for the HTTP client to executeString Remoteurl = "Http://**.**.***.***:8888/project/receiveservlet"; Postmethod Method=NewPostmethod (Remoteurl); //Multipart/form-data, boundary=---------------------------7de2b13a790640//method.addparameter ("Xmlhead", Xmlhead); //method.addparameter ("Xmlbody", xmlbody);HttpClient http_clinet=NewHttpClient (); synchronized(http_clinet) {Try            {                //send two independent two XML part, based on content-type= "Multipart/form-data" form, using multiple send modepart[] Parts = {NewStringpart ("Xmlhead", Xmlhead),NewStringpart ("Xmlbody", Xmlbody)};//both Stringpart and Filepart can be put in .Requestentity requestentity =Newmultipartrequestentity (Parts, Method.getparams ());                                Method.setrequestentity (requestentity); Method.getparams (). Setparameter (Httpmethodparams.so_timeout,30000); //link Timeout 30 secondsHttp_clinet.gethttpconnectionmanager (). Getparams (). Setconnectiontimeout (30000); //Read timeout 30 secondsHttp_clinet.gethttpconnectionmanager (). Getparams (). Setsotimeout (30000);                                Http_clinet.executemethod (method); String[] Result=NewString[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"; }}

Second, multipartrequest receiving parameters

 PackageCom.test.servlet;Importjava.io.IOException;ImportJava.io.PrintWriter;ImportJava.io.File;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.apache.log4j.Logger;Importcom.oreilly.servlet.MultipartRequest; Public classBossservletextendshttpservlet{/**Serialversionuid*/    PrivateLogger Logger = Logger.getlogger (bossservlet.class);  Public voiddoget (httpservletrequest request, httpservletresponse response)throwsIOException, servletexception { This. DoPost (request, response); }    protected voidDoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {//multipartrequestString head =NULL ; String Body=NULL ; Try{File Filedir=NewFile ( This. Getservletcontext (). Getrealpath ("/formhttp")); if(!filedir.exists ())            {Filedir.mkdirs (); }                        intInmaxpostsize = 10 * 1024 * 1024; //utf-8 Chinese encoding mode upload fileMultipartrequest multirequest =NewMultipartrequest (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 (); }        }    }     Public voidInit ()throwsservletexception {Super. Init (); }}

If a form based on content-type= "Multipart/form-data" is sent, but the parameter value is obtained through Request.getparameter ("* *"), the parameter value obtained is NULL.

HttpClient sending Multipart/form-data type parameters and receiving parameters with Multipartrequest

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.