Android uploads files in two ways. The first is HTTP-based httpurlconnection, and the second is TCP-based socket. The difference between the two methods is that there is a cache mechanism in the httpurlconnection when uploading. If a large file is uploaded, memory overflow occurs. If you use TCP socket to upload data, this problem will be solved.
HTTP: httpurlconnection
1. Open an httpurlconnection through the URL encapsulation path
2. Set the Request Method and header fields: Content-Type, Content-Length, host
3. Send spliced data
Example:
Private Static final string boundary = "------------------------- 7db1c523809b2"; // public Boolean uploadhttpurlconnection (string username, string password, string path) throws exception {// find the file = new file (environment. getexternalstoragedirectory (), PATH); // concatenate the stringbuilder sb = new stringbuilder (); sb. append ("--" + boundary + "\ r \ n"); sb. append ("content-dispositio N: Form-data; name = \ "USERNAME \" "+" \ r \ n "); sb. append ("\ r \ n"); sb. append (username + "\ r \ n"); sb. append ("--" + boundary + "\ r \ n"); sb. append ("content-Disposition: Form-data; name = \" password \ "" + "\ r \ n"); sb. append ("\ r \ n"); sb. append (password + "\ r \ n"); sb. append ("--" + boundary + "\ r \ n"); sb. append ("content-Disposition: Form-data; name = \" file \ "; filename = \" "+ path +" \ "" + "\ r \ n "); SB. append ("Content-Type: Image/pjpeg "+" \ r \ n "); sb. append ("\ r \ n"); byte [] Before = sb. tostring (). getbytes ("UTF-8"); byte [] After = ("\ r \ n --" + boundary + "-- \ r \ n "). getbytes ("UTF-8"); Url url = new URL ("http: // 192.168.1.16: 8080/14 _ Web/servlet/loginservlet"); httpurlconnection conn = (httpurlconnection) URL. openconnection (); Conn. setrequestmethod ("Post"); Conn. setrequestproperty ("Content-Type", "multipart/form-data; boundary =" + Boundary); Conn. setrequestproperty ("Content-Length", String. valueof (before. length + file. length () + after. length); Conn. setrequestproperty ("host", "192.168.1.16: 8080"); Conn. setdooutput (true); outputstream out = Conn. getoutputstream (); inputstream in = new fileinputstream (File); out. write (Before); byte [] Buf = new byte [1024]; int Len; while (LEN = in. read (BUF ))! =-1) out. write (BUF, 0, Len); out. write (after); In. close (); out. close (); Return Conn. getresponsecode () == 200 ;}
TCP socket
1. We can use socket to send TCP requests to send uploaded data in segments.
Example:
Public Boolean uploadbysocket (string username, string password, string path) throws exception {// find the file = new file (environment. getexternalstoragedirectory (), PATH); // stringbuilder sb = new stringbuilder (); sb. append ("--" + boundary + "\ r \ n"); sb. append ("content-Disposition: Form-data; name = \" USERNAME \ "" + "\ r \ n"); sb. append ("\ r \ n"); sb. append (username + "\ r \ n"); sb. A Ppend ("--" + boundary + "\ r \ n"); sb. append ("content-Disposition: Form-data; name = \" password \ "" + "\ r \ n"); sb. append ("\ r \ n"); sb. append (password + "\ r \ n"); sb. append ("--" + boundary + "\ r \ n"); sb. append ("content-Disposition: Form-data; name = \" file \ "; filename = \" "+ path +" \ "" + "\ r \ n "); SB. append ("Content-Type: image/pjpeg" + "\ r \ n"); sb. append ("\ r \ n"); // data before the file byte [] Before = sb. tostring (). getbytes ("Ut F-8 "); // Data byte after file [] After = (" \ r \ n -- "+ boundary +" -- \ r \ n "). getbytes ("UTF-8"); Url url = new URL ("http: // 192.168.1.199: 8080/14 _ Web/servlet/loginservlet"); // because data is cached in httpurlconnection, memory overflow occurs when uploading large files. Therefore, we use socket to transmit Socket socket = new socket (URL. gethost (), URL. getport (); outputstream out = socket. getoutputstream (); printstream PS = new printstream (Out, true, "UTF-8"); // write the request header ps. println ("post/14 _ Web/servlet/loginservlet HTTP/1.1 "); PS. println ("Content-Type: multipart/form-data; boundary =" + boundary); PS. println ("Content-Length:" + String. valueof (before. length + file. length () + after. length); PS. println ("Host: 192.168.1.199: 8080"); inputstream in = new fileinputstream (File); // write data out. write (Before); byte [] Buf = new byte [1024]; int Len; while (LEN = in. read (BUF ))! =-1) Out. Write (BUF, 0, Len); Out. Write (after); in. Close (); Out. Close (); Return true ;}
Build a server and complete the upload function
Package CN. test. web. servlet; 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 loginservlet extends httpservlet {Private Static final long serialversionuid = 1l; @ overridepublic void doget (httpservletrequest request, response) throws handle, ioexception {dopost (request, response );} @ overridepublic void dopost (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {Boolean ismultipart = servletfileupload. ismultipartcontent (request); If (ismultipart) Try {fileitemfactory factory = new diskfileitemfactory (); servletfileupload upload = new servletfileupload (factory); List <fileitem> items = upload. parserequest (request); file dir = new file (request. getsession (). getservletcontext (). getrealpath ("/WEB-INF/upload"); // create directory dir. mkdir (); For (fileitem item: Items) if (item. isformfield () system. out. println (item. getfieldname () + ":" + item. getstring (); else {item. write (new file (Dir, item. getname (). substring (item. getname (). lastindexof ("\") + 1);} catch (exception e) {e. printstacktrace ();} else {system. out. println (request. getmethod (); system. out. println (request. getparameter ("username"); system. out. println (request. getparameter ("password "));}}}