Java backend mock-up form submission

Source: Internet
Author: User
Tags date now

Code enables processing of text fields and non-text fields

Request Code:

/** * Upload * * @param urlstr * @param textmap * @param filemap * @return */public s Tatic string Formupload (String urlstr, map<string, string> Textmap, map<string, string> Filemap)          {String res = "";          HttpURLConnection conn = null; String boundary = "---------------------------123821742118716";              Boundary is the delimiter of the request header and the content of the uploaded file 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 +" \ "\ \ \ \ \ \ \");                        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 ();              Read return data 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 ("error sending post request.              "+ urlstr);          E.printstacktrace ();                  } finally {if (conn! = null) {conn.disconnect ();              conn = null;      }} return res; }

To process the upload request code:

/** * Upload * @param request * @param response * @throws Exception */public void Doupload (HttpServletRequest request, Httpser Vletresponse response) throws Exception {String jsession = Request.getparameter ("Jsessionid"); System.out.println (jsession); HttpSession s = request.getsession (); System.out.println (S.getid ());D iskfileitemfactory factory = new Diskfileitemfactory ();//Set memory buffers, After writing the temporary file Factory.setsizethreshold (10240000); Servletfileupload upload = new Servletfileupload (factory);//Set maximum upload value for individual files Upload.setfilesizemax (10002400000l);// Sets the maximum value for the entire 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;D ate date = new Date (); Iterator iter = Items.iterator (); String fileName = Tmpfilepath + file.separator +date.geTtime (); while (Iter.hasnext ()) {//loop gets each form item Fileitem item = (Fileitem) iter.next (); if (Item.isformfield ()) {String name = Item.getfieldname (); try {String value = item.getstring ("Utf-8");//If the parameter contains Chinese, it prevents garbled map.put (name, value);} catch ( Unsupportedencodingexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} else if (item.getname (). Length () > 0) {String namefix = Item.getname (); namefix = Namefix.substring ( Namefix.lastindexof (".")); filename = filename +namefix;item.write (new File);}} 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 ();}}

To test the calling code:

/**      * @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);                  }

  

Java backend mock-up form submission

Related Article

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.