Uploading files to the server using the HTTP protocol in Android

Source: Internet
Author: User

First we need to send the data using the HTTP protocol, we need to know the HTTP send upload file to the server when the header fields are required to have the relevant configuration, see


This is a request to upload a file to the server using the browser simulation, we can see that it contains the request header field and the entity part, but one more---------------------------7da2137580612, it is actually a dividing line, Used to separate the entity data, he will include more than two "-" when using separate entity data, and at the end of the time will be in addition to the previous two minus "-", but also at the end of the two minus "-" indicates the end. For the first time, in the header field of Content-type, you can see that his header field is "Multipart/form-data" because the server will accept the file and save it only if the Content-type header field is set to that value. Then his composition is: The Request header field + two carriage return line (\ r \ n), then the divider (remember to add two minus) after a carriage return line (\ r \ n), then two carriage return line, to the data value, followed by the divider line, so go down

The general idea to implement this function: because it is about the operation of the network, not directly in the UI thread execution, so open a thread to complete the upload function (about the breakpoint upload and then share with you). Then the thread must be aware of the need to add a looper that belongs to the thread, or the program will crash. Then control the download in the C layer of MVC. The process of downloading code is mostly difficult in how to group the request data, the hardest water content-length the value of this header field. However, it is possible to calculate his value by content-length= the text + file.

Here is the specific code implementation:

Mainactivity.java, his main function is to provide an interface, then there is a button and three input frame, click on the button to upload the file, when the file is located in the root directory of the SD card and upload, otherwise just upload title and length. He opened a sub-thread to complete the task of uploading. There are four main methods in this class, namely

1,public Static Boolean Save (string title, string length), for files that need to be uploaded do not exist but can upload title and length

2,public Static Boolean Save (string title, string length, file UploadFile), when the uploaded file exists, it is called to upload the method

3,private Static Boolean Sendhttpclientpostrequest (string path, map<string, string> params, string encoding) Used to send a GET or POST request, called by the first Save method

4,public static Boolean post (String path, map<string, string> params, formfile[] files) is used to upload a file and is called by the second Save method.

public class Mainactivity extends activity{/* upload file title */private EditText titletext;/* uploaded length */private EditText lengthtext;/ * uploaded file name */private EditText nametext; @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.main); titletext = (EditText) This.findviewbyid (r.id.title); lengthText = (EditText) This.findviewbyid (r.id.timelength); nametext = (EditText) This.findviewbyid (r.id.filename);} /** * After clicking the Save button the user will upload the file * @param v button */public void Save (View v) {String filename = Nametext.gettext (). toString (); String title = Titletext.gettext (). toString (); String length = Lengthtext.gettext (). toString (); Uploadthread uploadthread = new Uploadthread (filename, title, length, this); Uploadthread.start ();}} @SuppressLint ("Showtoast") class Uploadthread extends thread{string filename; String title; String length; Context Context;public Uploadthread (string filename, string title, string length, context context) {super (); This.filena me = filename;this.tItle = Title;this.length = Length;this.context = Context;} @Overridepublic void Run () {/* * detects an SD card, media_mounted indicates that the SD object is present and has read/write permissions * media_mounted_read_only indicates that the SD card is read only */ Looper.prepare (); if (Environment.getexternalstoragestate (). Equals (environment.media_mounted) | | Environment.getexternalstoragestate (). Equals (environment.media_mounted_read_only)) {File UploadFile = new File ( Environment.getexternalstoragedirectory (), filename),//located under the root directory, the file name is Filenameif (uploadfile.exists ()) {Boolean result = Newsservice.save (title, length, uploadfile);//upload if file exists, including title,length already fileif (result) {Toast.maketext ( Context, r.string.success, 1). Show ();} Else{toast.maketext (Context, R.string.error, 1). Show ();}} Else{toast.maketext (Context, r.string.filenoexsit, 1). Show ();}} Else{boolean result = Newsservice.save (title, length);//If the file does not exist, it simply uploads title and Lengthif (result) {Toast.maketext (context , r.string.success, 1). Show ();} Else{toast.maketext (Context, R.string.error, 1). Show ();}} Looper.loop ();}}
Service class

public class Newsservice {/** * Save data This is when the upload is not successful when calling * @param title * @param length * @return */public Static Boolean Save (string title, string length) {String path = "Http://192.168.0.168:8080/web/ManageServlet"; map<string, string> params = new hashmap<string, string> ();p arams.put ("title", title);p Arams.put (" Timelength ", length); try {return sendhttpclientpostrequest (path, params," UTF-8 ");} catch (Exception e) { E.printstacktrace ();} return false;} /** * Sending a POST request via httpclient can also be sent directly using GET or POST request * @param path Request path * @param params request parameter * @param encoding encoding * @return request is No success */private Static Boolean sendhttpclientpostrequest (string path, map<string, string> params, string encoding) th Rows exception{list<namevaluepair> pairs = new arraylist<namevaluepair> ();//Store request parameter if (Params!=null & &!params.isempty ()) {for (map.entry<string, string> entry:params.entrySet ()) {Pairs.add (new Basicnamevaluepair (Entry.getkey (), Entry.getvalue ()));}} Urlencodedformentity entity = new Urlencodedformentity (pairs, encoding); HttpPost HttpPost = new HttpPost (path), httppost.setentity (entity);D efaulthttpclient client = new Defaulthttpclient (); HttpResponse response = Client.execute (HttpPost); if (Response.getstatusline (). Getstatuscode () = = () {return true;} return false;} /** * Upload file * @param title file name * @param length * @param uploadfile file * @return */public static Boolean save (String tit Le, string length, File uploadfile) {string path = "Http://192.168.1.125:8080/web/ManagerServlet"; map<string, string> params = new hashmap<string, string> ();p arams.put ("title", title);p Arams.put (" Timelength ", length); Formfile formfile = new Formfile (UploadFile, "Videofile", "image/gif");//Specifies the type of upload file try {return post (path, params, new Form file[]{formfile});} catch (Exception e) {e.printstacktrace ();} return false;} /** * Real implementation of the upload file class * @param path upload path, that is, the path of the server, can be the domain name * @param params request parameter key is the parameter name, value is the parameter value * @param file[] Upload the file, can be more than */&lt ;p re name= "code" class= "Java"> public static Boolean post (String path, map<string, string> params, formfile[] files) {final string Boundary = "---------------------------7da2137580612"; Data separator Line Final String endline = "--" + Boundary + "--\r\n";//Data end flag, followed by a carriage return newline symbol int filedatalength = 0;for (Formfile Uploa Dfile:files) {//Get the total length of file type data, join when a colleague uploads multiple files, you need to use the iteration, each iteration is calculated the HTTP length of a file StringBuilder fileexplain = new StringBuilder (); Fileexplain.append ("--"); Fileexplain.append (boundary); Fileexplain.append ("\ r \ n");// Content-disposition This header field is used to set the default name when the user cannot get the correct file name, and sometimes it is returned from the server to the user. This is when the user downloads data from the server but fails to get the file name, which is also used as the default name for the file Fileexplain.append ("content-disposition:form-data;name=\" "+ Uploadfile.getparametername () + "\"; filename=\ "" + uploadfile.getfilname () + "\" \ \ \ \ \ \ \ \ "); Fileexplain.append (" Content-type: "+ uploadfile.getcontenttype () +" \r\n\r\n "); Filedatalength + = Fileexplain.length (); if ( Uploadfile.getinstream ()! = null) {filedatalength + = Uploadfile.getfile (). Length ();} else{filedatalength + = UPLOadfile.getdata (). length;} Filedatalength + = "\ r \ n". Length ();} StringBuilder textentity = new StringBuilder (); for (map.entry<string, string> entry:params.entrySet ()) {// Constructs the Entity data of the text type parameter Textentity.append ("--"); Textentity.append (boundary); Textentity.append ("\ r \ n"); Textentity.append (" Content-disposition:form-data; Name=\ "" + entry.getkey () + "\" \r\n\r\n ") Textentity.append (Entry.getvalue ()); Textentity.append (" \ r \ n ");} Calculates the total length of the entity data transferred to the server int datalength = textentity.tostring (). GetBytes (). length + filedatalength + endline.getbytes (). Length Socket socket = Null;outputstream OutStream = null; BufferedReader reader = null;try{url url = new URL (path), int port = url.getport () = = 1? 80:url.getport (); socket = new Socket (Inetaddress.getbyname (Url.gethost ()), port), OutStream = Socket.getoutputstream ();//complete HTTP request Header send string below Requestmethod = "POST" + url.getpath () + "http/1.1\r\n"; Outstream.write (Requestmethod.getbytes ()); String accept = "Accept:image/gif, Image/jpeg, Image/pjpeg, Image/pjpeg, Application/x-shockwave-flash, Application/xaml+xml, Application/vnd.ms-xpsdocument, APPLICATION/X-MS-XBAP, Application/x-ms-application, Application/vnd.ms-excel, Application/vnd.ms-powerpoint, Application/msword, */*\r\n "; Outstream.write (Accept.getbytes ()); String language = "accept-language:zh-cn\r\n"; Outstream.write (Language.getbytes ()); String contenttype = "CONTENT-TYPE:MULTIPART/FORM-DATA; boundary= "+ boundary +" \ r \ n "; Outstream.write (Contenttype.getbytes ()); String contentlength = "Content-length:" + datalength + "\ r \ n"; Outstream.write (Contentlength.getbytes ()); String alive = "connection:keep-alive\r\n"; Outstream.write (Alive.getbytes ()); String host = "Host:" + url.gethost () + ":" + port + "\ r \ n"; Outstream.write (Host.getbytes ());//After writing the HTTP request header, write a carriage return in accordance with the HTTP protocol. Line Outstream.write ("\ r \ n". GetBytes ());//Send the Entity data of all text types Outstream.write (textentity.tostring (). GetBytes ());// Send Entity data for all file types out for (Formfile uploadfile:files) {StringBuilder fileentity = new StringBuilder (); Fileentity.appenD ("--"); Fileentity.append (boundary); Fileentity.append ("\ r \ n"); Fileentity.append ("Content-disposition:form-data ; name=\ "" + uploadfile.getparametername () + "\"; filename=\ "" + uploadfile.getfilname () + "\" \ \ \ \ \ \ \ \ \ \ \ ") Fileentity.append (" Content-type: "+ uploadfile.getcontenttype () +" \r\n\r\n "); Outstream.write (Fileentity.tostring (). GetBytes ()); if ( Uploadfile.getinstream ()! = null) {byte[] buffer = new Byte[1024];int len = 0;while (len = Uploadfile.getinstream (). Read (b Uffer, 0, 1024x768))! =-1) {outstream.write (buffer, 0, Len);} Uploadfile.getinstream (). Close ();} Else{outstream.write (Uploadfile.getdata (), 0, Uploadfile.getdata (). length); Outstream.write ("\ r \ n". GetBytes ());} The data end flag is sent below, indicating that the data has ended Outstream.write (Endline.getbytes ()); reader = new BufferedReader (New InputStreamReader ( Socket.getinputstream ())); if (Reader.readline (). IndexOf ("200") = = 1) {//Read the data returned by the Web server to determine if the request code is 200, if not 200, Representative request failed return false;} Outstream.flush ();} catch (Malformedurlexception e) {e.printstacktrace ();} catch (UnknownhostexcePtion e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} Finally{try{outstream.close ();} catch (IOException e) {e.printstacktrace ();} Try{reader.close ();} catch (IOException e) {e.printstacktrace ();} Try{socket.close ();} catch (IOException e) {e.printstacktrace ();}} return true;}

}


This allows the file upload function to be implemented.

Uploading files to the server using the HTTP protocol in Android

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.