Android uploads file data via HTTP protocol _android

Source: Internet
Author: User
Tags flush gettext

This example for you to share the Android through the HTTP protocol to upload the file data of the specific code for your reference, the specific contents are as follows

Sockethttprequester.java

Package cn.itcast.utils;
Import Java.io.BufferedReader;
Import Java.io.ByteArrayOutputStream;
Import Java.io.DataOutputStream;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.io.OutputStream;
Import java.net.HttpURLConnection;
Import java.net.InetAddress;
Import Java.net.Socket;
Import Java.net.URL;
Import Java.net.URLEncoder;
Import java.util.ArrayList;
Import java.util.List;

Import Java.util.Map;
Import Org.apache.http.HttpResponse;
Import Org.apache.http.NameValuePair;
Import org.apache.http.client.HttpClient;
Import org.apache.http.client.entity.UrlEncodedFormEntity;
Import Org.apache.http.client.methods.HttpPost;
Import org.apache.http.impl.client.DefaultHttpClient;

Import Org.apache.http.message.BasicNameValuePair; public class Sockethttprequester {/** * send XML Data * @param path request address * @param XML XML data * @param encoding encoding * @retur
n * @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.d O "enctype=" Multipart/form-data "> <input type=" text "name=" NAME "> <input type=" text "name=" id "> <i Nput type= "File" name= "ImageFile"/> <input type= "file" name= "Zip"/> </FORM> * @param path upload path (note: Avoid using localhost or 127.0.0.1 such a path test, as it will point to the phone simulator, you can use HTTP://WWw.itcast.cn or http://192.168.1.10:8080 path test) * @param params request parameter key is the parameter name, value is the parameters value * @param file upload/public Stati C Boolean post (String path, map<string, string> params, formfile[] files) throws exception{final String Boun Dary = "---------------------------7da2137580612";
    Data separator Line Final String endline = "--" + Boundary + "--\r\n";//Data end sign int filedatalength = 0;
     for (Formfile uploadfile:files) {//Get the total length of the file type data 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;
    } StringBuilder textentity = new StringBuilder ();
      For (map.entry<string, string> entry:params.entrySet ()) {//Construct Entity data for text type parameters 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 transmitted to the server int datalength = textentity.tostring (). GetBytes (). length + filedatalength + endline.getbytes (
    
    ). length;
    URL url = new URL (path); int port = Url.getport () ==-1?
    80:url.getport ();    
    Socket socket = new Socket (Inetaddress.getbyname (Url.gethost ()), port);
    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 ()); 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 the HTTP request header is written, a carriage return line outstream.write ("\ r \ n") is written according to the HTTP protocol. GetBytes ()); Send all text-type Entity Data 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 ());
      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 ()));
    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, the request failed 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.itcast.cn or http://192 168.1.10:8080 such path test) * @param params request parameter key is parameter name, value is the value of parameters * @param file Upload file/public static Boolean post (String Path, map<string, string> params, formfile file) throws exception{return post (path, params, new Formfile[]{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.itcast.cn 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[] Postfromht Tpclient (string path, map<string, string> params, string encode) throws Exception{list<namevaluepair> formparams = new arraylist<namevaluepair> ()//is used to hold the request parameter for (map.entry<string,
 String> Entry:params.entrySet ()) {Formparams.add (New Basicnamevaluepair (Entry.getkey (), Entry.getvalue ()));
 } urlencodedformentity entity = new Urlencodedformentity (formparams, encode);
 HttpPost HttpPost = new HttpPost (path);
 Httppost.setentity (entity); HttpClient httpclient = new Defaulthttpclient ();//As browser HttpResponse response = Httpclient.execute (HttpPost);
 Send POST request return Readstream (Response.getentity (). getcontent ()); /** * Send request * @param path Request path * @param params request parameter key for parameter name value is parameter value * @param the encoding of the encode request parameter */public static B Yte[] Post (string path, map<string, string> params, String encode) throws exception{-//string params = "Method=save &name= "+ urlencoder.encode (" Old bi "," UTF-8 ") +" &age=28& ";//Required parameters to send StringBuilder Parambuilder = new
 StringBuilder (""); if (Params!=null &&!params.isempty ()) {for (MAP.ENTRY&LT String, string> Entry:params.entrySet ()) {Parambuilder.append (Entry.getkey ()). Append ("="). Append (Urlencoder.en
  Code (Entry.getvalue (), encode)). Append ("&");
 } Parambuilder.deletecharat (Parambuilder.length ()-1);
 } byte[] data = parambuilder.tostring (). GetBytes ();
 URL url = new URL (path);
 HttpURLConnection conn = (httpurlconnection) url.openconnection ();
 Conn.setdooutput (TRUE);//allow outgoing request parameter conn.setusecaches (FALSE);//No Caching 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;. NETCLR 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 (InputStream i
 Nstream) 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 ();

 }
}

Formfile.java

Package cn.itcast.utils;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;

Import Java.io.InputStream;
 /** * Upload File/public class Formfile {/* Upload file Data * * Private byte[];
 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";
 Public Formfile (String filname, byte[] data, String parametername, String contentType) {this.data = data;
 This.filname = Filname;
 This.parametername = parametername;
 if (contenttype!=null) This.contenttype = 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 () {return parametername;
 } public void SetParameterName (String parametername) {this.parametername = parametername;
 Public String getContentType () {return contentType;
 } public void setContentType (String contentType) {this.contenttype = ContentType;

 }
 
}

Streamtool.java

Package cn.itcast.utils;

Import Java.io.ByteArrayOutputStream;
Import Java.io.InputStream;

public class Streamtool {

 /**
 * Reads data from the input stream
 * @param instream *
 @return *
 @throws Exception
 * * Public
 Static byte[] Readinputstream (InputStream instream) throws exception{
 Bytearrayoutputstream Outsteam = new Bytearrayoutputstream ();
 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 ();
 }


Mainactivity.java

Package cn.itcast.uploaddata;
Import Java.io.File;
Import Java.util.HashMap;

Import Java.util.Map;
Import Cn.itcast.net.HttpRequest;
Import Cn.itcast.utils.FormFile;
Import Cn.itcast.utils.SocketHttpRequester;
Import android.app.Activity;
Import Android.os.Bundle;
Import android.os.Environment;
Import Android.util.Log;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.EditText;

Import Android.widget.Toast;
  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);
    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 = Titl
  Etext.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 {//Httprequest.sendgetrequest ("http://192.168.1.100:8080/videoweb/video/manage.do", params, "UTF-8");
   File UploadFile = new file (Environment.getexternalstoragedirectory (), Videotext.gettext (). toString ());
   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 ());  }
  }
 });

 }
}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.