The Android side uploads files to the server via HttpURLConnection
Source: Internet
Author: User
<span id="Label3"></p><p><p><span style="font-size:18px;">The Android side uploads files to the server via HttpURLConnection</span></p></p><p><p><span style="font-size:18px;">One: the principle of realization</span></p></p><p><p><span style="font-size:18px;">Recently in the application development of Android client, involving to upload images to the background server, chose to do the Spring3 MVC HTTP API as a background upload interface, Android Client I choose to use HttpURLConnection to submit file data through form upload function, originally wanted to search online copy of the changes to the code is good, found there is no ready-made example, Most of the examples are based on httpclient or based on the Base64 encoding as a string to transfer image data, so I have to do my own, referring to some online information, the final implementation of the HttpURLConnection upload files based on the Android client code, Less nonsense, in fact, based on the httpurlconnection implementation of file upload the most important thing is to be familiar with the HTTP protocol knowledge, know the MIME file block in the HTTP protocol format, the basic transmission data format is as Follows:</span></p></p><p><p><br></p></p><p><p></p></p><p><p><span style="font-size:18px;">Where boundary represents the boundary of the form, as long as the content bytes are written in the format of the HttpURLConnection object output stream, The Server-side spring Controller will automatically respond to the acceptance, and follow the browser page upload file is the Same.</span></p></p><span style="font-size:18px;"><span style="font-size:18px;">server-side http API, I am the controller based on SPRING3 MVC implementation, The code is as Follows:</span></span><br><p><p></p></p><pre code_snippet_id="1562630" snippet_file_name="blog_20160122_1_424882" name="code" class="java">@RequestMapping (value = "/uploadmyimage/{token}", method = Requestmethod.post) public @ResponseBody String Getuploadfile (httpservletrequest request, httpservletresponse response, @PathVariable String token) {logger.info (" Spring3 MVC upload file with Multipart form ") logger.info (" servlet context path: "+ request.getsession (). getservletconte XT (). Getrealpath ("/")); Userdto profiledto = Userservice.getuserbytoken (token); String Imguuid = ""; try {if (request instanceof multiparthttpservletrequest && profiledto.gettoken () = Null) {Mul Tiparthttpservletrequest multipartrequest = (multiparthttpservletrequest) request;logger.info ("spring3 MVC upload File with Multipart form ");//does not work, oh my god!! Multipartfile file = Multipartrequest.getfiles ("myfile"). get (0); inputstream input = File.getinputstream (); long FileSize = File.getsize (); BufferedImage image = Imageio.read (input),//create data transfer objectimagedto DTO = new Imagedto ();d to.setcreatedate (n EW Date ());d to.setfilename (file. getoriginalfilename ());d to.setimage (image);d to.setcreator (profiledto.getusername ());d to.setfilesize (fileSize) ;d to.settype (ImageAttachmentType.CLIENT_TYPE.getTitle ());d to.setuuid (uuid.randomuuid (). toString ());///save to Dbimguuid = imageservice.createimage (dto); input.close ();}} Catch (Exception e) {e.printstacktrace (); logger.error ("upload image error", e);} Return imguuid;}</pre><p><p></p></p><p><p><span style="font-size:18px;">The Android client implements the uploaded code based on the httpurlconnection, and I encapsulate it into a separate class file so that you can use it directly, just by passing in parameters such as the uploaded url. The code is as Follows:</span></p></p><pre code_snippet_id="1562630" snippet_file_name="blog_20160122_2_1013526" name="code" class="java">Package Com.demo.http;import Java.io.bufferedinputstream;import Java.io.dataoutputstream;import java.io.File; Import Java.io.fileinputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.net.httpurlconnection;import Java.net.url;import Java.util.random;import Android.os.Handler;import Android.util.base64;import Android.util.log;public class Uploadimagetask implements Apiurlconstants {private String Requesturl = domain_address + upload_design_image_url; Defaultprivate final String CRLF = "\ r \ n";p rivate Handler handler;private string token;public uploadimagetask (string to ken, Handler Handler) {this.handler = Handler;this.token = token;} Public String Execute (file...files) {inputstream inputstream = null; HttpURLConnection URLConnection = null; FileInputStream FileInput = Null;dataoutputstream requeststream = null;handler.sendemptymessage (+); try {//open Connectionurl url = new URL (requesturl.replace ("{token}", this.token); urlconnection = (httpurlconnection) Url.openconnection ();//create random boundaryrandom random = new Random (); byte[] randombytes = new Byte[16];random.nextbytes (rand ombytes); String boundary = base64.encodetostring (randombytes, base64.no_wrap);/* for POST request */urlconnection.setdooutput ( true); urlconnection.setdoinput (true); urlconnection.setusecaches (false); urlconnection.setrequestmethod ("POST"); Long size = (files[0].length ()/1024x768), if (size >=) {handler.sendemptymessage ( -150); return "error";} Build entity Formurlconnection.setrequestproperty ("Connection", "keep-alive"); Urlconnection.setrequestproperty (" Content-type "," multipart/form-data;boundary= "+ boundary); urlconnection.setrequestproperty (" Cache-Control "," No-cache ");//never try to chunked mode, need to set a lot of things//if (size > Page) {//urlconnection.setchunkedstr Eamingmode (0);//}//else {//urlconnection.setfixedlengthstreamingmode ((int) files[0].length ());//}//end Comment by Zhigang on 2016-01-19/* upload file stream */fileinput = new FileInputStream (files[0]); requeststream = new DataOutputStream (urlconnection.getoutputstream ()); String Nikename = "myfile"; requeststream = new DataOutputStream (urlconnection.getoutputstream ()); Requeststream.writebytes ("--" + boundary + CRLF); requeststream.writebytes ("content-disposition:form-data; Name=\ "" + nikename + "\"; Filename=\ "" + files[0].getname () + "\" "+ CRLF) requeststream.writebytes (" content-type: "+ getmimetype (files[0]) + CRLF ); requeststream.writebytes (CRLF);//write Image byte contents int bytesread;byte[] buffer = new Byte[8192];handler.sendemptymessage (50) ; while ((bytesread = Fileinput.read (buffer))! =-1) {requeststream.write (buffer, 0, bytesread);} Requeststream.flush (); requeststream.writebytes (CRLF); requeststream.flush (); requeststream.writebytes ("--" + Boundary + "--" + CRLF); Requeststream.flush (); fileinput.close ();//try to get responseint StatusCode = Urlconnection.getr Esponsecode (); If (statusCode = =) {inputstream = new Bufferedinputstream (urlconnection.getinputstream ()); String Imageuuid = HTTPUTil.convertinputstreamtostring (inputstream); LOG.I ("image-uuid", "uploaded image uuid:" + imageuuid); handler.sendemptymessage (); return imageuuid;}} Catch (Exception e) {e.printstacktrace ();} finally {if (inputstream! = Null) {try {inputstream.close ();} catch (ioexceptio n E) {e.printstacktrace ();}} If (requeststream! = Null) {try {requeststream.close ();} catch (ioexception e) {e.printstacktrace ()}} If (fileInput! = Null) {try {fileinput.close ();} catch (ioexception e) {e.printstacktrace ()}} If (urlconnection! = Null) {urlconnection.disconnect ();}} Handler.sendemptymessage (); return null;} Private String getmimetype (file file) {String fileName = file.getname (); if (filename.endswith ("png") | | Filename.endswith ("PNG")) {return "image/png";} else {return "image/jpg";}}}</pre><span style="font-size:18px;"><span style="font-size:18px;">after I test, the effect of the leverage!! So please forget httpclient this thing, Android development no longer need it anymore. </span></span><p><p><br></p></p><p><p>The Android side uploads files to the server via HttpURLConnection</p></p></span>
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