This article illustrates how Android programming uses HTTP protocol and TCP protocol to upload files. Share to everyone for your reference, specific as follows:
There are two ways to upload files to Android, the first is based on the HTTP protocol httpurlconnection, and the second is the socket based on the TCP protocol. The difference between these two approaches is that there is a caching mechanism inside when uploading with httpurlconnection, and if uploading larger files can cause memory overflow. If the use of TCP protocol socket upload will solve this disadvantage.
HTTP protocol HttpURLConnection
1. Open a httpurlconnection via URL encapsulation path
2. Set the request mode and header field: Content-type, Content-length, Host
3. Splicing data to send
Example:
Private static final String boundary = "---------------------------7db1c523809b2";//Data Split Line public boolean Uploadhttpurlconnection (string Username, string password, string path) throws Exception {//Find files on sdcard file = n
EW File (environment.getexternalstoragedirectory (), path);
Imitation HTTP protocol sends data way to splice 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.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 protocol Socket
1. We can send a TCP request using the socket and send the uploaded data in a segmented
Example:
public boolean Uploadbysocket (string username, string password, string path) throws Exception {//Find files in SDcard based on path
File File = new file (environment.getexternalstoragedirectory (), path);
Data before assembling form fields and files 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.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");
The data before the file byte[] before = Sb.tostring (). GetBytes ("UTF-8");
The data after the file byte[] after = ("\r\n--" + boundary + "--\r\n"). GetBytes ("UTF-8"); URL url = new URL ("http://192.168.1.199:8080/14_Web/sErvlet/loginservlet ");
Because the data will be cached in HttpURLConnection, the memory overflow will be caused by uploading large files, so we use the socket to transfer the socket socket = new Socket (Url.gethost (), Url.getport ());
OutputStream out = Socket.getoutputstream ();
PrintStream PS = new PrintStream (out, True, "UTF-8");
Write out the request Head 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 the server, 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; @Override public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, ioexcept
Ion {DoPost (request, response); @Override public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioex
ception {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"));
}
}
}
I hope this article will help you with your Android programming.