Android simulates HTTP multipart/form-Data Request protocol information to upload images

Source: Internet
Author: User
Problem: In Android apps, when entering user information, posting comments, and so on, it is inevitable that you will encounter the "Form operation" (similar to the web form operation) Upload image function. In this case, httpconnection/apachehttp of Android cannot be implemented through post and get methods. Solution: the android client simulates the HTTP multipart/form-Data Request protocol to upload images. /*** File name: uploadimage. Java ** copyright: Apache license, version 2.0 ** Function Description: Implements image file upload. ** Creation date: 2011-5-10 ** Author: Bert LEE * // ** modification history: */public class uploadimage {string multipart_form_data = "multipart/form-Data "; string twohyphens = "--"; string boundary = "****************** fd4fh3gl0hk7ai6"; // data delimiter string lineend = system. getproperty ("line. separator "); // The value is" \ r \ n "in windows. /** upload the image content. For the format, see http format." Program Call the http://wiki.dev.renren.com/wiki/Photos.upload#.E7.A8.8B.E5.BA.8F.E8.B0.83.E7.94.A8 * to explain its format very clearly. * Format: ** -- ******************* fd4fh3hk7ai6 * content-Disposition: Form-data; name = "upload_file "; filename = "apple.jpg" * Content-Type: image/JPEG ** here is the file content, in the form of a binary stream */private void addimagecontent (image [] files, dataoutputstream output) {for (image file: Files) {stringbuilder split = new stringbuilder (); split. append (twohyphens + boundary + lineend); split. append ("content-Disposition: Form-Data; Name = \ "" + file. getformname () + "\"; filename = \ "" + file. getfilename () + "\" "+ lineend); split. append ("Content-Type:" + file. getcontenttype () + lineend); split. append (lineend); try {// send image data output. writebytes (split. tostring (); output. write (file. getdata (), 0, file. getdata (). length); output. writebytes (lineend);} catch (ioexception e) {Throw new runtimeexception (E); }}/ ** construct the form field content. For the format, see HTTP protocol format (firebug can capture relevant data ). (To upload the parameter values corresponding to the form) * format is as follows: * -- ****************** fd4fh3hk7ai6 * content-Disposition: form-data; name = "action" * // empty row, which must have * upload */private void addformfield (set <map. entry <object, Object> Params, dataoutputstream output) {stringbuilder sb = new stringbuilder (); For (map. entry <object, Object> param: Params) {sb. append (twohyphens + boundary + lineend); sb. append ("content-Disposition: Form-data; Nam E = \ "" + Param. getkey () + "\" "+ lineend); sb. append (lineend); sb. append (Param. getvalue () + lineend);} Try {output. writebytes (sb. tostring (); // send form field data} catch (ioexception e) {Throw new runtimeexception (e) ;}/ *** submit data directly to the server through the HTTP protocol, implement the form submission function. * @ Param actionurl: Upload path * @ Param Params the request parameter key is the parameter name, value is the parameter value * @ Param files Upload File Information * @ return returns the request result */Public String post (string actionurl, set <map. entry <object, Object> Params, image [] files) {httpurlconnection conn = NULL; dataoutputstream output = NULL; bufferedreader input = NULL; try {URL url = new URL (actionurl); Conn = (httpurlconnection) URL. openconnection (); Conn. setconnecttimeout (1200 00); Conn. setdoinput (true); // allow the input of Conn. setdooutput (true); // allow the output of Conn. setusecaches (false); // do not use cache Conn. setrequestmethod ("Post"); Conn. setrequestproperty ("connection", "keep-alive"); Conn. setrequestproperty ("Content-Type", multipart_form_data + "; boundary =" + boundary); Conn. connect (); Output = new dataoutputstream (Conn. getoutputstream (); addimagecontent (files, output); // Add the image content addformf Ield (Params, output); // Add the form field content output. writebytes (twohyphens + boundary + twohyphens + lineend); // data end mark output. flush (); int code = Conn. getresponsecode (); If (code! = 200) {Throw new runtimeexception (" '" + actionurl + "' failed! ");} Input = new bufferedreader (New inputstreamreader (Conn. getinputstream (); stringbuilder response = new stringbuilder (); string oneline; while (oneline = input. readline ())! = NULL) {response. append (oneline + lineend);} return response. tostring ();} catch (ioexception e) {Throw new runtimeexception (E);} finally {// unified resource release try {If (output! = NULL) {output. Close () ;}if (input! = NULL) {input. Close () ;}catch (ioexception e) {Throw new runtimeexception (e) ;}if (Conn! = NULL) {Conn. disconnect () ;}} public static void main (string [] ARGs) {try {string response = ""; bufferedreader in = new bufferedreader (New filereader ("config/actionurl. properties "); string actionurl = in. readline (); // read the name of the field corresponding to the form and its value properties formdataparams = new properties (); formdataparams. load (New fileinputstream (new file ("config/formdataparams. properties "); set <map. entry <object, Object> Params = formdataparams. entryset (); // read the form field name and image path corresponding to the image. properties imageparams = new properties (); imageparams. load (New fileinputstream (new file ("config/imageparams. properties "); set <map. entry <object, Object> images = imageparams. entryset (); image [] files = new image [images. size ()]; int I = 0; For (map. entry <object, Object> image: Images) {image file = new image (image. getvalue (). tostring (), image. getkey (). tostring (); files [I ++] = file;} // image file = new image ("images/apple.jpg", "upload_file "); // image [] files = new image [0]; // files [0] = file; response = new uploadimage (). post (actionurl, Params, files); system. out. println ("returned result:" + response);} catch (ioexception e) {e. printstacktrace ();}}}
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.