In Android or J2EE background, you need to hang out on other people's website data. Simulating form submission is a very common thing, but in Android, you need to upload multiple files and upload with ordinary form fields. This may be a bit difficult. Today I spent time sorting out a tool class, mainly with the help of HttpClient. It is actually very simple. You can see the code very clearly.
HttpClient tool class:
package ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; /** * HttpClient tool class * * @author Zeng Fantian * @version 1.0 */ public class HttpClientUtil { public final static String Method_POST = "POST"; public final static String Method_GET = "GET"; /** * Multipart/form-data type form submission * * @param form * Form data */ public static String submitForm(MultipartForm form) { // Return string String responseStr = ""; // Create an HttpClient instance HttpClient httpClient = new DefaultHttpClient(); try { // Instantiate the submission request HttpPost httpPost = new HttpPost(()); // Create MultipartEntityBuilder MultipartEntityBuilder entityBuilder = (); // Append normal form fields Map<String, String> normalFieldMap = (); for (Iterator<Entry<String, String>> iterator = ().iterator(); ();) { Entry<String, String> entity = (); ((), new StringBody((), ("text/plain", Consts.UTF_8))); } // Append file fields Map<String, File> fileFieldMap = (); for (Iterator<Entry<String, File>> iterator = ().iterator(); ();) { Entry<String, File> entity = (); ((), new FileBody(())); } // Set the request entity (()); // Send a request HttpResponse response = (httpPost); int statusCode = ().getStatusCode(); // Get response data HttpEntity resEntity = (); if (200 == statusCode) { if (resEntity != null) { responseStr = (resEntity); } } } catch (Exception e) { ("Submitting the form failed, reason:" + ()); } finally { ().shutdown(); } return responseStr; } /** Form field Bean */ public class MultipartForm implements Serializable { /** Serial number */ private static final long serialVersionUID = -2138044819190537198L; /** Submit URL **/ private String action = ""; /** Submission method: POST/GET **/ private String method = "POST"; /** Normal form field **/ private Map<String, String> normalField = new LinkedHashMap<String, String>(); /** File field **/ private Map<String, File> fileField = new LinkedHashMap<String, File>(); public String getAction() { return action; } public void setAction(String action) { = action; } public String getMethod() { return method; } public void setMethod(String method) { = method; } public Map<String, String> getNormalField() { return normalField; } public void setNormalField(Map<String, String> normalField) { = normalField; } public Map<String, File> getFileField() { return fileField; } public void setFileField(Map<String, File> fileField) { = fileField; } public void addFileField(String key, File value) { (key, value); } public void addNormalField(String key, String value) { (key, value); } } }
The server-side method of uploading files and reading parameters: (Using the Apache fileupload component implementation, it realizes the three fields of obtaining methods: directly splicing parameters after the form action, form ordinary projects, and file projects)
In the background, I directly wrote a servlet, the specific code is as follows:
package ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; /** * File upload Servlet * @author Zeng Fantian */ public class ServletUploadFile extends HttpServlet { private static final long serialVersionUID = 1L; // Limit the upload size of files 1G private int maxPostSize = 1000 * 1024 * 10; public ServletUploadFile() { super(); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = (); String contextPath = ().getServletContext().getRealPath("/"); String webDir = "uploadfile" + + "images" + ; String systemPath = (); String basePath = () + "://" + () + ":" + ()+ systemPath + "/"; ("UTF-8"); ("text/html;charset=UTF-8"); try { DiskFileItemFactory factory = new DiskFileItemFactory(); (1024 * 4); // Set the write size ServletFileUpload upload = new ServletFileUpload(factory); (maxPostSize); // Set the maximum file upload size (()); //Get the parameters spliced after the action (such as: ?q=android) Enumeration enumList = (); while(()){ String key = (String)(); String value = (key); (key+"="+value); } //Get Submit Form Item List listItems = (request); Iterator iterator = (); while (()) { FileItem item = (FileItem) (); //Non-normal form items if (!()) { //Get the extension String ext = ().substring(().lastIndexOf("."), ().length()); String fileName = () + ext; File dirFile = new File(contextPath + webDir + fileName); if (!()) { ().mkdirs(); } (dirFile); ("fileName:" + () + "=====" + () + " size: "+ ()); ("The file has been saved to: " + contextPath + webDir + fileName); //Respond to client request (basePath + ("\\", "/") + fileName); (); }else{ //Ordinary form project ("Form Ordinary Item:"+()+"=" + ("UTF-8"));// Display the form content. ("UTF-8") can ensure that Chinese content is not garbled } } } catch (Exception e) { (); } finally { (); } } }
The tool class and server-side code are posted, so there is no need to say how to call it in detail, right? The package is clear enough
Calling sample DEMO:
//Create an HttpClientUtil instanceHttpClientUtil httpClient = new HttpClientUtil(); MultipartForm form = MultipartForm(); //Set form properties and parameters("http://192.168.1.7:8080/UploadFileDemo/cn/com/ajava/servlet/ServletUploadFile"); File photoFile = new File(sddCardPath+"//data//"); ("photo", photoFile); ("name", "Zeng Fantian"); ("tel", "15122946685"); //Submit the form(form);
Finally, let me explain the jar problem:
If you apply it in Android, you need to pay attention to the additional introduction of httpmime-4.3. (The one I downloaded at that time is the highest version). As for the jar of fileUpload, go to the official website of apache to download it directly
The above is all the content of this article. I hope that the content of this article will help you study or work. I also hope to support me more!