Android method for uploading file uploads based on HTTP protocol _android

Source: Internet
Author: User
Tags file upload flush gettext sqlite database

This article is an example of how Android implements file uploading based on HTTP protocol. Share to everyone for your reference, specific as follows:

Note The general use of HTTP protocol upload files are relatively small, generally less than 2M

Here's an example of uploading a small MP3 file

1. Main Activity:MainActivity.java

public class Mainactivity extends activity {private static final String TAG = "mainactivity";
  Private EditText Timelengthtext;
  Private EditText TitleText;
  Private EditText Videotext;
    @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.main);
    Submit the button button = (button) This.findviewbyid (R.id.button);
    Timelengthtext = (edittext) This.findviewbyid (r.id.timelength);
    Videotext = (edittext) This.findviewbyid (R.id.video);
    TitleText = (edittext) This.findviewbyid (r.id.title);
        Button.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {
        String title = Titletext.gettext (). toString ();
        String timelength = Timelengthtext.gettext (). toString ();
        map<string, string> params = new hashmap<string, string> ();
        Params.put ("Method", "save");
        Params.put ("title", title); ParamS.put ("Timelength", timelength); try {//Get SDcard directory File uploadfile = new file (Environment.getexternalstoragedirectory (), vide
          Otext.gettext (). toString ());
          Upload audio files Formfile formfile = new Formfile ("02.mp3", UploadFile, "video", "Audio/mpeg");
          Sockethttprequester.post ("Http://192.168.1.100:8080/videoweb/video/manage.do", params, formfile);
        Toast.maketext (Mainactivity.this, r.string.success, 1). Show ();
          catch (Exception e) {toast.maketext (Mainactivity.this, R.string.error, 1). Show ();
        LOG.E (TAG, e.tostring ());
  }
      }
    });

 }
}

2. Upload Tool class , notice inside the construct protocol string needs to be processed according to different submitting forms

public class Sockethttprequester {/** * sending XML Data * @param path request address * @param XML XML data * @param encoding encoding  * @return * @throws Exception/public static byte[] Postxml (string path, string XML, String encoding) throws
    exception{byte[] data = xml.getbytes (encoding);
    URL url = new URL (path);
    HttpURLConnection conn = (httpurlconnection) url.openconnection ();
    Conn.setrequestmethod ("POST");
    Conn.setdooutput (TRUE); Conn.setrequestproperty ("Content-type", "text/xml;
    charset= "+ encoding);
    Conn.setrequestproperty ("Content-length", String.valueof (Data.length));
    Conn.setconnecttimeout (5 * 1000);
    OutputStream OutStream = Conn.getoutputstream ();
    Outstream.write (data);
    Outstream.flush ();
    Outstream.close ();
    if (Conn.getresponsecode () ==200) {return Readstream (Conn.getinputstream ());
  return null; /** * Submit data directly to the server through the HTTP protocol to implement the following form submission function: * <form method=post action= "Http://192.168.0.200:8080/ssi/filEload/test.do "enctype=" Multipart/form-data "> <input type=" text "name=" NAME "> <input type=" text "N Ame= ' id ' > <input type= ' file ' name= ' imagefile '/> <input ' type= ' file ' name= ' Zip '/>
   Gt * @param path Upload route (note: Avoid using path tests such as localhost or 127.0.0.1, * because it will point to the phone simulator, you can use http://www.baidu.com or http://192.168.1.1 0:8,080 such path test) * @param params request parameter key is the parameter name, value is the argument value * @param file Upload file/public static Boolean post (String p Ath, map<string, string> params, formfile[] files throws Exception {//Data divider final String boundary = "---
    ------------------------7da2137580612 ";
    The data end sign "---------------------------7da2137580612--" final String endline = "--" + Boundary + "--/r/n";
    The following two for loops are all for data length parameters, depending on the type of the form///First get the total length of the file type data (including the file split line) int filedatalength = 0;
      for (Formfile uploadfile:files) {StringBuilder fileexplain = new StringBuilder ();
     Fileexplain.append ("--"); Fileexplain.append (boundary);
      Fileexplain.append ("/r/n"); Fileexplain.append ("content-disposition:form-data;name=/" "+ uploadfile.getparametername () +"/"; filename=/" "+
      Uploadfile.getfilname () + "/"/r/n ");
      Fileexplain.append ("Content-type:" + uploadfile.getcontenttype () + "/r/n/r/n");
      Fileexplain.append ("/r/n");
      Filedatalength + + fileexplain.length ();
      if (Uploadfile.getinstream ()!=null) {filedatalength + = Uploadfile.getfile (). Length ();
      }else{Filedatalength + = Uploadfile.getdata (). length;
    }}//re-construct the entity data for the text type parameter StringBuilder textentity = new StringBuilder ();
      For (map.entry<string, string> entry:params.entrySet ()) {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"); }//Calculation transmission toTotal Entity Data length of the server (total text length + data length + separator) int datalength = Textentity.tostring (). GetBytes (). length + filedatalength + endline.getby
    TES (). length;
    URL url = new URL (path); The default port number can actually not write int port = Url.getport () ==-1?
    80:url.getport ();
    Create a socket link socket socket = new Socket (Inetaddress.getbyname (Url.gethost ()), port);
    Get an output stream (from Android to the web) outputstream OutStream = Socket.getoutputstream ();
    The following completes the HTTP request header send String Requestmethod = "POST" + url.getpath () + "http/1.1/r/n";
    Outstream.write (Requestmethod.getbytes ()); Build Accept String Accept = "Accept:image/gif, Image/jpeg, Image/pjpeg, Image/pjpeg, Application/x-shockwave-flash, AP Plication/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 ());
    Constructing language String language = "accept-language:zh-cn/r/n"; Outstream.write (lAnguage.getbytes ()); Build contenttype String ContentType = "CONTENT-TYPE:MULTIPART/FORM-DATA;
    boundary= "+ boundary+"/r/n ";
    Outstream.write (Contenttype.getbytes ());
    Build contentlength String contentlength = "Content-length:" + datalength + "/r/n";
    Outstream.write (Contentlength.getbytes ());
    Constructing Alive String Alive = "connection:keep-alive/r/n";
    Outstream.write (Alive.getbytes ());
    Build host String host = "Host:" + url.gethost () + ":" + port + "/r/n";
    Outstream.write (Host.getbytes ());
    After the HTTP request header is written, a carriage return line outstream.write ("/r/n") is written according to the HTTP protocol. GetBytes ());
    Send the Entity data of all text types Outstream.write (textentity.tostring (). GetBytes ());
      The Entity data for all file types is sent 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 () +"/"/r/n");
      Fileentity.append ("Content-type:" + uploadfile.getcontenttype () + "/r/n/r/n");
      Outstream.write (Fileentity.tostring (). GetBytes ());
        Side-Read Write if (Uploadfile.getinstream ()!=null) {byte[] buffer = new byte[1024];
        int len = 0;
        while (len = Uploadfile.getinstream (). Read (buffer, 0, 1024))!=-1) {outstream.write (buffer, 0, Len);
      } uploadfile.getinstream (). Close ();
      else {outstream.write (uploadfile.getdata (), 0, Uploadfile.getdata (). length);
    } outstream.write ("/r/n". GetBytes ());
    Send the data end sign below, indicating that the data has been terminated outstream.write (Endline.getbytes ());
    BufferedReader reader = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));
    Read the data returned by the Web server to determine if the request code is 200, if not 200, to represent the request failure if (Reader.readline (). IndexOf (")" ==-1) {return false;
    } outstream.flush ();
    Outstream.close (); reader.clOSE ();
    Socket.close ();
  return true; /** * Submit data to Server * @param path upload path (note: Avoid using path tests such as localhost or 127.0.0.1, as it will point to the phone simulator, you can use http://www.baidu.com or http:// 192.168.1.10:8080 this path test) * @param params request parameter key is the parameter name, value is the argument value * @param file Upload/public static Boolean PO St (String Path, map<string, string> params, formfile file) throws Exception {return post (path, params, new Fo
  Rmfile[]{file}); /** * Submit data to Server * @param path upload path (note: Avoid using path tests such as localhost or 127.0.0.1, as it will point to the phone simulator, you can use http://www.baidu.com or http:// 192.168.1.10:8080 this path test) * @param params request parameter key is the parameter name, value is the argument value * @param encode encoding/public static byte[] Pos Tfromhttpclient (string path, map<string, string> params, string encode) throws Exception {//For storing request parameter List
    <NameValuePair> formparams = new arraylist<namevaluepair> (); For (map.entry<string, string> entry:params.entrySet ()) {Formparams.add (new Basicnamevaluepair (entry.get Key (), Entry.getvalue ());
    } urlencodedformentity entity = new Urlencodedformentity (formparams, encode);
    HttpPost HttpPost = new HttpPost (path);
    Httppost.setentity (entity);
    As a browser httpclient httpclient = new Defaulthttpclient ();
    Send POST request HttpResponse response = Httpclient.execute (HttpPost);
  Return Readstream (Response.getentity (). getcontent ()); /** * Send request * @param path Request path * @param params request parameter key is the parameter name value of the parameter value * @param the encoding of the encode request parameter * * * Publ IC static byte[] Post (string path, map<string, string> params, String encode) throws Exception {//string para ms = "Method=save&name=" + urlencoder.encode ("Old bi", "UTF-8") + "&age=28&"; the parameters to be sent StringBuilder Parambuild
    ER = new StringBuilder ("");
      if (Params!=null &&!params.isempty ()) {for (map.entry<string, string> entry:params.entrySet ()) {Parambuilder.append (Entry.getkey ()). Append ("="). Append (urlencoder.encodE (Entry.getvalue (), encode)). Append ("&");
    } Parambuilder.deletecharat (Parambuilder.length ()-1);
    } byte[] data = parambuilder.tostring (). GetBytes ();
    URL url = new URL (path);
    HttpURLConnection conn = (httpurlconnection) url.openconnection ();
    Set Conn.setdooutput (True) to allow outgoing request parameters;
    Set to not cache Conn.setusecaches (false);
    Conn.setconnecttimeout (5 * 1000);
    Conn.setrequestmethod ("POST"); The following sets HTTP request headers Conn.setrequestproperty ("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, */* ");
    Conn.setrequestproperty ("Accept-language", "ZH-CN"); Conn.setrequestproperty ("User-agent", "mozilla/4.0" (compatible; MSIE 8.0; Windows NT 5.2; trident/4.0. NET CLR 1.1.4322;. NET CLR 2.0.50727;. NET CLR 3.0.04506.30;. NET CLR 3.0.4506.2152. NET CLR 3.5.30729) ");
    Conn.setrequestproperty ("Content-type", "application/x-www-form-urlencoded");
    Conn.setrequestproperty ("Content-length", String.valueof (Data.length));
    Conn.setrequestproperty ("Connection", "keep-alive");
    Send parameter DataOutputStream outstream = new DataOutputStream (Conn.getoutputstream ());
    Outstream.write (data)//Send the Parameters out Outstream.flush ();
    Outstream.close ();
    if (Conn.getresponsecode () ==200) {return Readstream (Conn.getinputstream ());
  return null; /** * Read Stream * @param instream * @return byte array * @throws Exception/public static byte[] Readstream (INP
    Utstream instream) throws Exception {Bytearrayoutputstream Outsteam = new Bytearrayoutputstream ();
    byte[] buffer = new byte[1024];
    int len =-1;
    while ((Len=instream.read (buffer))!=-1) {outsteam.write (buffer, 0, Len);
    } outsteam.close ();
    Instream.close ();
  return Outsteam.tobytearray (); }
}
public class Streamtool {/** * reads data from the input stream * @param instream * @return * @throws Exception/Public STA Tic byte[] Readinputstream (InputStream instream) throws exception{bytearrayoutputstream Outsteam = new BYTEARRAYOUTPU
    Tstream ();
    byte[] buffer = new byte[1024];
    int len = 0;
    while (len = instream.read (buffer))!=-1) {outsteam.write (buffer, 0, Len);
    } outsteam.close ();
    Instream.close ();
  return Outsteam.tobytearray ();
  }/** * Use JavaBean package upload file Data * * */public class Formfile {//upload file Data private byte[] data;
  Private InputStream instream;
  private file file;
  File name private String filname;
  Request parameter name private String parametername;
  Content Type Private String ContentType = "Application/octet-stream"; /** * Upload small files, the file data first read into memory * @param filname * @param data * @param parametername * @param contentType * * p Ublic formfile (String filname, byte[] data, String parametername, String contentType) {this.data = data;
    This.filname = Filname;
    This.parametername = parametername;
  if (contenttype!=null) This.contenttype = ContentType; /** * Upload large file, while reading file data upload * @param filname * @param file * @param parametername * @param contentType *
    /Public Formfile (string filname, File file, String parametername, String contentType) {this.filname = Filname;
    This.parametername = parametername;
    This.file = file;
    try {this.instream = new FileInputStream (file);
    catch (FileNotFoundException e) {e.printstacktrace ();
  } if (contenttype!=null) This.contenttype = ContentType;
  Public file GetFile () {return file;
  Public InputStream Getinstream () {return instream;
  Byte[] GetData () {return data;
  Public String Getfilname () {return filname;
  } public void Setfilname (String filname) {this.filname = Filname; Public String Getparametername () {returnParameterName;
  } public void SetParameterName (String parametername) {this.parametername = parametername;
  Public String getContentType () {return contentType;
  } public void setContentType (String contentType) {this.contenttype = ContentType;

 }
}

More interested readers of Android related content can view this site: "Android file Operation tips Summary", "Android operation SQLite Database Skills Summary", "Android operation JSON format Data techniques Summary", " Android Database Operating skills summary, "Android Programming activity Operation Skills Summary", "Android programming SD Card Operation method Summary", "Android Development introduction and Advanced Course", "Android Resource Operation skills Summary", " Android View tips Summary and a summary of the use of Android controls

I hope this article will help you with the Android program.

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.