Simulate POST upload in Java background
POST upload integration simulation in the background
Description: The Java background simulates post requests, sends parameters, uploads files, and other methods. This method is applicable to some public API 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) {// String filepath = F: \ 2.png; String urlStr = http: /localhost: 8080/wxchar_menu/upload; Map
TextMap = new HashMap
(); TextMap. put (name, testname); Map
FileMap = new HashMap
(); // The fileMap parameter that can be written at will. 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
TextMap, Map
FileMap) {String res =; HttpURLConnection conn = null; String BOUNDARY = ------------------------- 123821742118716; // boundary is the separator between the request header and the content of the uploaded file. try {URL url = new URL (urlStr); conn = (HttpURLConnection) url. openConnection (); conn. setConnectTimeout (5000); conn. setreadtimeouts (30000); conn. setDoOutput (true); conn. setDoInput (true); conn. setUseCaches (false); conn. setRequestMethod (POST); conn. setRequestPrope Rty (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 (). append (--). append (BOUNDARY ). append (); strBuf. append (Content-Disposition: form-data; name = + inputName + \ R); 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 (). append (--). append (BOUNDARY ). append (); strBuf. append (Content-Disposition: form-data; name = + inputName +; filename = + filename + \ r); strBuf. append (Content-Type: + contentType +); out. write (strBuf. toString (). getBytes (); Dat AInputStream 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 = (-- + BOUNDARY + --). getBytes (); out. write (endData); out. flush (); out. close (); // data returns StringBuffer strBuf = new StringBuffer (); BufferedReader reader = new BufferedReader (new InputStreamReader (conn. getInputStream (); String line = null; while (line = reader. readLine ())! = Null) {strBuf. append (line ). append ();} 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 following on the page:
Accept in the background
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, response) throws ServletException, IOException {String title = request. getParameter (title); String timelength = request. getParameter (timel Ength); 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 the temporary directory // factory. setSizeThreshold (1024*8); // The 8 K buffer. If the file is larger than 8 K, it is saved to the temporary directory ServletFileUpload upload = new ServletFileUpload (factory); upload. setHeaderEncoding (UTF-8); // upload. setFileSizeMax (1024*1024*10*2); // set the maximum size of each file to 20 mb. // upload. setSizeMax (1024*1024*100); // you can upload up to 100 MList files.
Items = upload. parseRequest (request); String dir = request. getSession (). getServletContext (). getRealPath (/files); // File dirFile = new File (dir); // File dirFile = new File (e: // downFiles); if (! DirFile. exists () dirFile. mkdirs (); for (FileItem item: items) {if (item. isFormField () {// if the text type parameter String name = item. getFieldName (); String value = item. getString (UTF-8); System. out. println (name + = + value);} else {// if the file type parameter is System. out. println (dir); File saveFile = new File (dirFile, item. getName (); item. write (saveFile) ;}} catch (Exception e) {e. printStackTrace () ;}} else {doGet (request, response );}}}