Java simulates the post method and submits a form to upload images.

Source: Internet
Author: User

Article Title: using java post to simulate form submission for Image Upload

 

Author: javaboy2012
Email: yanek@163.com
Qq: 1046011462

 

 

The html of the simulated form is as follows:

 

<Form action = "up_result.jsp" method = "post" enctype = "multipart/form-data" name = "form1" id = "form1">
 
<Label>
<Input type = "text" name = "name" value = ""/>
</Label>

<Label>
<Input type = "file" name = "userfile"/>
</Label>

<Label>
<Input type = "submit" value = "Upload"/>
</Label>
</Form>

 

 

The java code is as follows:

 

Package com. yanek. util; 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; im Port net. sf. json. JSONArray; import net. sf. json. JSONObject; public class HttpPostUploadUtil {/*** @ param args */public static void main (String [] args) {String filepath = "E: \ ziliao \ 0.jpg "; string urlStr = "http: // 127.0.0.1: 8080/minicms/up/up_result.jsp"; Map <String, String> textMap = new HashMap <String, String> (); textMap. put ("name", "testname"); Map <String, String> fileMap = new HashMap <String, String> (); FileMap. put ("userfile", filepath); String ret = formUpload (urlStr, textMap, fileMap); System. out. println (ret);}/*** upload image ** @ 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 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. setRequestProperty ("Connection", "Keep-Alive"); conn. setRequestProperty ("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; z H-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; n Ame = \ "" + inputName + "\" \ 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 (); 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 the returned 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 ("An error occurred while sending the POST request. "+ UrlStr); e. printStackTrace ();} finally {if (conn! = Null) {conn. disconnect (); conn = null ;}} return res ;}}

 

 

 

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.