background analog post upload integration
Introduction : Java background simulation POST request, send parameters and upload files, and other methods, applicable to some public API interface calls.
Send Request
Background
Package Org.lives.platform.upload.utils;import Java.io.bufferedreader;import Java.io.datainputstream;import Java.io.dataoutputstream;import Java.io.file;import Java.io.fileinputstream;import Java.io.InputStreamReader; Import Java.io.outputstream;import java.net.httpurlconnection;import Java.net.url;import Java.util.HashMap;import Java.util.iterator;import Java.util.map;import Javax.activation.mimetypesfiletypemap;import Org.junit.Test;import Org.liufeng.weixin.pojo.accesstoken;import Org.liufeng.weixin.util.weixinutil;import Net.sf.json.JSONArray; Import Net.sf.json.jsonobject;public class Httppostuploadutil {/** * @param args */public static void main (string[] args) {//File address to upload string filepath = "F:\\2.png"; String urlstr = "Http://localhost:8080/wxchar_menu/upload"; map<string, string> textmap = new hashmap<string, string> (); Textmap.put ("Name", "TestName"); map<string, string> filemap = new hashmap<string, string> (); Arbitrarily written parameter filemap.put ("UserFile", filepath); String ret = formupload (Urlstr, Textmap, Filemap); SYSTEM.OUT.PRINTLN (ret);} /** * * @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 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, 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 ());//Textif (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 ());} Fileif (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 ());D atainputstream 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 ();// Data returned 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) {e.printstacktrace ();} finally {if (conn! = null) {Conn.disconnect (); conn = null;}} return res;}}
This effect is equivalent to the page:
<form action= "/wxchar_menu/upload" method= "post" enctype= "Multipart/form-data" ><label> <input type= " Text "name=" name "value=" name "/></label> <label> <input type=" file "Name=" UserFile "/></label > <label> <input type= "Submit" value= "Up"/></label></form>
Background Acceptance
Package Org.lives.platform.upload.utils;import Java.io.file;import Java.io.ioexception;import java.util.List; Import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.apache.commons.fileupload.fileitem;import Org.apache.commons.fileupload.fileitemfactory;import Org.apache.commons.fileupload.disk.diskfileitemfactory;import Org.apache.commons.fileupload.servlet.servletfileupload;public class Manageservlet extends HttpServlet {private Static final Long serialversionuid = 1l;protected void doget (httpservletrequest request,httpservletresponse response) Throws Servletexception, IOException {String title = Request.getparameter ("title"); String timelength = Request.getparameter ("Timelength"); System.out.println ("Video name:" + title); System.out.println ("duration:" + timelength);} protected void DoPost (HttpServletRequest request,httpservletresponse response) throws Servletexception, ioexceptIon {Boolean ismultipart = servletfileupload.ismultipartcontent (request); if (Ismultipart) {try {fileitemfactory Factory = new Diskfileitemfactory ();// File Filetemp = new file ("d:/a");// if (! Filetemp.exists ()) {filetemp.mkdirs ();} factory.setrepository (New File ("d:/a") ));///Set TEMP directory// Factory.setsizethreshold (1024*8)/////8k buffer, file greater than 8K is saved to temp directory servletfileupload upload = new Servletfileupload (factory ); Upload.setheaderencoding ("UTF-8");// Upload.setfilesizemax (1024 * 1024 * 10*2)////set each file up to 20m// upload.setsizemax (1024 * 1024 * 100);////You can upload up to 100mlist<fileitem> items = upload.parserequest (request); String dir = request.getsession (). Getservletcontext (). Getrealpath ("/files");//File Dirfile = new file (dir);// There is a local e disk under File Dirfile = new file ("E://downfiles"), if (!dirfile.exists ()) dirfile.mkdirs (); for (Fileitem Item:items) {if (Item.isformfield ()) {//If the text type parameter is string name = Item.getfieldname (); String value = item.getstring ("UTF-8"); SYSTEM.OUT.PRINTLN (name + "=" + value);} else {//If file type parameter System.out.println (dir); File SaveFile = new file (Dirfile, Item.getname ()); Item.write (SaveFile);}}} catch (Exception e) {e.printstacktrace ();}} else {doget (request, Response);}}}
the jar required
http://download.csdn.net/detail/u014201191/8829429
Java background Simulation Post upload