[Android開發]Android之使用Http協議實現文件上傳功能

注意一般使用Http協議上傳的文件都比較小,一般是小於2M

這裏示例是上傳一個小的MP3文件

1.主Activity:MainActivity.java

  1. public class MainActivity extends Activity   
  2. {  
  3.     private static final String TAG = "MainActivity";  
  4.     private EditText timelengthText;  
  5.     private EditText titleText;  
  6.     private EditText videoText;  
  7.       
  8.     @Override  
  9.     public void onCreate(Bundle savedInstanceState)   
  10.     {  
  11.        super.onCreate(savedInstanceState);  
  12.        setContentView(R.layout.main);  
  13.        //提交上傳按鈕  
  14.        Button button = (Button) this.findViewById(R.id.button);  
  15.        timelengthText = (EditText) this.findViewById(R.id.timelength);  
  16.        videoText = (EditText) this.findViewById(R.id.video);  
  17.        titleText = (EditText) this.findViewById(R.id.title);  
  18.        button.setOnClickListener(new View.OnClickListener()   
  19.        {              
  20.             @Override  
  21.             public void onClick(View v)   
  22.             {  
  23.                 String title = titleText.getText().toString();  
  24.                 String timelength = timelengthText.getText().toString();  
  25.                 Map<String, String> params = new HashMap<String, String>();  
  26.                 params.put("method""save");  
  27.                 params.put("title", title);  
  28.                 params.put("timelength", timelength);  
  29.                 try   
  30.                 {                     
  31.                     //得到SDCard的目錄  
  32.                     File uploadFile = new File(Environment.getExternalStorageDirectory(), videoText.getText().toString());  
  33.                     //上傳音頻文件  
  34.                     FormFile formfile = new FormFile("02.mp3", uploadFile, "video""audio/mpeg");  
  35.                     SocketHttpRequester.post("http://192.168.1.100:8080/videoweb/video/manage.do", params, formfile);  
  36.                     Toast.makeText(MainActivity.this, R.string.success, 1).show();  
  37.                 }  
  38.                 catch (Exception e)   
  39.                 {  
  40.                     Toast.makeText(MainActivity.this, R.string.error, 1).show();  
  41.                     Log.e(TAG, e.toString());  
  42.                 }  
  43.             }  
  44.         });          
  45.     }  
  46. }  
 

2.上傳工具類,注意裏面構造協議字符串需要根據不同的提交表單來處理

  1. public class SocketHttpRequester   
  2. {  
  3.     /** 
  4.      * 發送xml數據 
  5.      * @param path 請求地址 
  6.      * @param xml xml數據 
  7.      * @param encoding 編碼 
  8.      * @return 
  9.      * @throws Exception 
  10.      */  
  11.     public static byte[] postXml(String path, String xml, String encoding) throws Exception{  
  12.         byte[] data = xml.getBytes(encoding);  
  13.         URL url = new URL(path);  
  14.         HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  15.         conn.setRequestMethod("POST");  
  16.         conn.setDoOutput(true);  
  17.         conn.setRequestProperty("Content-Type""text/xml; charset="+ encoding);  
  18.         conn.setRequestProperty("Content-Length", String.valueOf(data.length));  
  19.         conn.setConnectTimeout(5 * 1000);  
  20.         OutputStream outStream = conn.getOutputStream();  
  21.         outStream.write(data);  
  22.         outStream.flush();  
  23.         outStream.close();  
  24.         if(conn.getResponseCode()==200){  
  25.             return readStream(conn.getInputStream());  
  26.         }  
  27.         return null;  
  28.     }  
  29.       
  30.     /** 
  31.      * 直接通過HTTP協議提交數據到服務器,實現如下面表單提交功能: 
  32.      *   <FORM METHOD=POST ACTION="http://192.168.0.200:8080/ssi/fileload/test.do" enctype="multipart/form-data"> 
  33.             <INPUT TYPE="text" NAME="name"> 
  34.             <INPUT TYPE="text" NAME="id"> 
  35.             <input type="file" name="imagefile"/> 
  36.             <input type="file" name="zip"/> 
  37.          </FORM> 
  38.      * @param path 上傳路徑(注:避免使用localhost或127.0.0.1這樣的路徑測試, 
  39.      *                  因爲它會指向手機模擬器,你可以使用http://www.baidu.com或http://192.168.1.10:8080這樣的路徑測試) 
  40.      * @param params 請求參數 key爲參數名,value爲參數值 
  41.      * @param file 上傳文件 
  42.      */  
  43.     public static boolean post(String path, Map<String, String> params, FormFile[] files) throws Exception  
  44.     {     
  45.         //數據分隔線  
  46.         final String BOUNDARY = "---------------------------7da2137580612";   
  47.         //數據結束標誌"---------------------------7da2137580612--"  
  48.         final String endline = "--" + BOUNDARY + "--/r/n";  
  49.           
  50.         //下面兩個for循環都是爲了得到數據長度參數,依據表單的類型而定  
  51.         //首先得到文件類型數據的總長度(包括文件分割線)  
  52.         int fileDataLength = 0;  
  53.         for(FormFile uploadFile : files)  
  54.         {  
  55.             StringBuilder fileExplain = new StringBuilder();  
  56.             fileExplain.append("--");  
  57.             fileExplain.append(BOUNDARY);  
  58.             fileExplain.append("/r/n");  
  59.             fileExplain.append("Content-Disposition: form-data;name=/""+ uploadFile.getParameterName()+"/";filename=/""+ uploadFile.getFilname() + "/"/r/n");  
  60.             fileExplain.append("Content-Type: "+ uploadFile.getContentType()+"/r/n/r/n");  
  61.             fileExplain.append("/r/n");  
  62.             fileDataLength += fileExplain.length();  
  63.             if(uploadFile.getInStream()!=null){  
  64.                 fileDataLength += uploadFile.getFile().length();  
  65.             }else{  
  66.                 fileDataLength += uploadFile.getData().length;  
  67.             }  
  68.         }  
  69.         //再構造文本類型參數的實體數據  
  70.         StringBuilder textEntity = new StringBuilder();          
  71.         for (Map.Entry<String, String> entry : params.entrySet())   
  72.         {    
  73.             textEntity.append("--");  
  74.             textEntity.append(BOUNDARY);  
  75.             textEntity.append("/r/n");  
  76.             textEntity.append("Content-Disposition: form-data; name=/""+ entry.getKey() + "/"/r/n/r/n");  
  77.             textEntity.append(entry.getValue());  
  78.             textEntity.append("/r/n");  
  79.         }  
  80.           
  81.         //計算傳輸給服務器的實體數據總長度(文本總長度+數據總長度+分隔符)  
  82.         int dataLength = textEntity.toString().getBytes().length + fileDataLength +  endline.getBytes().length;  
  83.           
  84.         URL url = new URL(path);  
  85.         //默認端口號其實可以不寫  
  86.         int port = url.getPort()==-1 ? 80 : url.getPort();  
  87.         //建立一個Socket鏈接  
  88.         Socket socket = new Socket(InetAddress.getByName(url.getHost()), port);  
  89.         //獲得一個輸出流(從Android流到web)  
  90.         OutputStream outStream = socket.getOutputStream();  
  91.         //下面完成HTTP請求頭的發送  
  92.         String requestmethod = "POST "+ url.getPath()+" HTTP/1.1/r/n";  
  93.         outStream.write(requestmethod.getBytes());  
  94.         //構建accept  
  95.         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";  
  96.         outStream.write(accept.getBytes());  
  97.         //構建language  
  98.         String language = "Accept-Language: zh-CN/r/n";  
  99.         outStream.write(language.getBytes());  
  100.         //構建contenttype  
  101.         String contenttype = "Content-Type: multipart/form-data; boundary="+ BOUNDARY+ "/r/n";  
  102.         outStream.write(contenttype.getBytes());  
  103.         //構建contentlength  
  104.         String contentlength = "Content-Length: "+ dataLength + "/r/n";  
  105.         outStream.write(contentlength.getBytes());  
  106.         //構建alive  
  107.         String alive = "Connection: Keep-Alive/r/n";          
  108.         outStream.write(alive.getBytes());  
  109.         //構建host  
  110.         String host = "Host: "+ url.getHost() +":"+ port +"/r/n";  
  111.         outStream.write(host.getBytes());  
  112.         //寫完HTTP請求頭後根據HTTP協議再寫一個回車換行  
  113.         outStream.write("/r/n".getBytes());  
  114.         //把所有文本類型的實體數據發送出來  
  115.         outStream.write(textEntity.toString().getBytes());           
  116.           
  117.         //把所有文件類型的實體數據發送出來  
  118.         for(FormFile uploadFile : files)  
  119.         {  
  120.             StringBuilder fileEntity = new StringBuilder();  
  121.             fileEntity.append("--");  
  122.             fileEntity.append(BOUNDARY);  
  123.             fileEntity.append("/r/n");  
  124.             fileEntity.append("Content-Disposition: form-data;name=/""+ uploadFile.getParameterName()+"/";filename=/""+ uploadFile.getFilname() + "/"/r/n");  
  125.             fileEntity.append("Content-Type: "+ uploadFile.getContentType()+"/r/n/r/n");  
  126.             outStream.write(fileEntity.toString().getBytes());  
  127.             //邊讀邊寫  
  128.             if(uploadFile.getInStream()!=null)  
  129.             {  
  130.                 byte[] buffer = new byte[1024];  
  131.                 int len = 0;  
  132.                 while((len = uploadFile.getInStream().read(buffer, 01024))!=-1)  
  133.                 {  
  134.                     outStream.write(buffer, 0, len);  
  135.                 }  
  136.                 uploadFile.getInStream().close();  
  137.             }  
  138.             else  
  139.             {  
  140.                 outStream.write(uploadFile.getData(), 0, uploadFile.getData().length);  
  141.             }  
  142.             outStream.write("/r/n".getBytes());  
  143.         }  
  144.         //下面發送數據結束標誌,表示數據已經結束  
  145.         outStream.write(endline.getBytes());          
  146.         BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));  
  147.         //讀取web服務器返回的數據,判斷請求碼是否爲200,如果不是200,代表請求失敗  
  148.         if(reader.readLine().indexOf("200")==-1)  
  149.         {  
  150.             return false;  
  151.         }  
  152.         outStream.flush();  
  153.         outStream.close();  
  154.         reader.close();  
  155.         socket.close();  
  156.         return true;  
  157.     }  
  158.       
  159.     /**  
  160.      * 提交數據到服務器  
  161.      * @param path 上傳路徑(注:避免使用localhost或127.0.0.1這樣的路徑測試,因爲它會指向手機模擬器,你可以使用http://www.baidu.com或http://192.168.1.10:8080這樣的路徑測試)  
  162.      * @param params 請求參數 key爲參數名,value爲參數值  
  163.      * @param file 上傳文件  
  164.      */  
  165.     public static boolean post(String path, Map<String, String> params, FormFile file) throws Exception  
  166.     {  
  167.        return post(path, params, new FormFile[]{file});  
  168.     }  
  169.     /** 
  170.      * 提交數據到服務器 
  171.      * @param path 上傳路徑(注:避免使用localhost或127.0.0.1這樣的路徑測試,因爲它會指向手機模擬器,你可以使用http://www.baidu.com或http://192.168.1.10:8080這樣的路徑測試) 
  172.      * @param params 請求參數 key爲參數名,value爲參數值 
  173.      * @param encode 編碼 
  174.      */  
  175.     public static byte[] postFromHttpClient(String path, Map<String, String> params, String encode) throws Exception  
  176.     {  
  177.         //用於存放請求參數  
  178.         List<NameValuePair> formparams = new ArrayList<NameValuePair>();  
  179.         for(Map.Entry<String, String> entry : params.entrySet())  
  180.         {  
  181.             formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));  
  182.         }  
  183.         UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, encode);  
  184.         HttpPost httppost = new HttpPost(path);  
  185.         httppost.setEntity(entity);  
  186.         //看作是瀏覽器  
  187.         HttpClient httpclient = new DefaultHttpClient();  
  188.         //發送post請求    
  189.         HttpResponse response = httpclient.execute(httppost);     
  190.         return readStream(response.getEntity().getContent());  
  191.     }  
  192.     /** 
  193.      * 發送請求 
  194.      * @param path 請求路徑 
  195.      * @param params 請求參數 key爲參數名稱 value爲參數值 
  196.      * @param encode 請求參數的編碼 
  197.      */  
  198.     public static byte[] post(String path, Map<String, String> params, String encode) throws Exception  
  199.     {  
  200.         //String params = "method=save&name="+ URLEncoder.encode("老畢", "UTF-8")+ "&age=28&";//需要發送的參數  
  201.         StringBuilder parambuilder = new StringBuilder("");  
  202.         if(params!=null && !params.isEmpty())  
  203.         {  
  204.             for(Map.Entry<String, String> entry : params.entrySet())  
  205.             {  
  206.                 parambuilder.append(entry.getKey()).append("=")  
  207.                     .append(URLEncoder.encode(entry.getValue(), encode)).append("&");  
  208.             }  
  209.             parambuilder.deleteCharAt(parambuilder.length()-1);  
  210.         }  
  211.         byte[] data = parambuilder.toString().getBytes();  
  212.         URL url = new URL(path);  
  213.         HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  214.         //設置允許對外發送請求參數  
  215.         conn.setDoOutput(true);  
  216.         //設置不進行緩存  
  217.         conn.setUseCaches(false);  
  218.         conn.setConnectTimeout(5 * 1000);  
  219.         conn.setRequestMethod("POST");  
  220.         //下面設置http請求頭  
  221.         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, */*");  
  222.         conn.setRequestProperty("Accept-Language""zh-CN");  
  223.         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)");  
  224.         conn.setRequestProperty("Content-Type""application/x-www-form-urlencoded");  
  225.         conn.setRequestProperty("Content-Length", String.valueOf(data.length));  
  226.         conn.setRequestProperty("Connection""Keep-Alive");  
  227.           
  228.         //發送參數  
  229.         DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());  
  230.         outStream.write(data);//把參數發送出去  
  231.         outStream.flush();  
  232.         outStream.close();  
  233.         if(conn.getResponseCode()==200)  
  234.         {  
  235.             return readStream(conn.getInputStream());  
  236.         }  
  237.         return null;  
  238.     }  
  239.       
  240.     /**  
  241.      * 讀取流  
  242.      * @param inStream  
  243.      * @return 字節數組  
  244.      * @throws Exception  
  245.      */  
  246.     public static byte[] readStream(InputStream inStream) throws Exception  
  247.     {  
  248.         ByteArrayOutputStream outSteam = new ByteArrayOutputStream();  
  249.         byte[] buffer = new byte[1024];  
  250.         int len = -1;  
  251.         while( (len=inStream.read(buffer)) != -1)  
  252.         {  
  253.             outSteam.write(buffer, 0, len);  
  254.         }  
  255.         outSteam.close();  
  256.         inStream.close();  
  257.         return outSteam.toByteArray();  
  258.     }  
  259. }  
 

  1. public class StreamTool   
  2. {  
  3.     /** 
  4.      * 從輸入流讀取數據 
  5.      * @param inStream 
  6.      * @return 
  7.      * @throws Exception 
  8.      */  
  9.     public static byte[] readInputStream(InputStream inStream) throws Exception{  
  10.         ByteArrayOutputStream outSteam = new ByteArrayOutputStream();  
  11.         byte[] buffer = new byte[1024];  
  12.         int len = 0;  
  13.         while( (len = inStream.read(buffer)) !=-1 ){  
  14.             outSteam.write(buffer, 0, len);  
  15.         }  
  16.         outSteam.close();  
  17.         inStream.close();  
  18.         return outSteam.toByteArray();  
  19.     }  
  20. }  
 

  1. /** 
  2.  * 使用JavaBean封裝上傳文件數據 
  3.  *  
  4.  */  
  5. public class FormFile   
  6. {  
  7.     //上傳文件的數據   
  8.     private byte[] data;  
  9.     private InputStream inStream;  
  10.     private File file;  
  11.     //文件名稱   
  12.     private String filname;  
  13.     //請求參數名稱  
  14.     private String parameterName;  
  15.     //內容類型  
  16.     private String contentType = "application/octet-stream";  
  17.       
  18.     /** 
  19.      * 上傳小文件,把文件數據先讀入內存 
  20.      * @param filname 
  21.      * @param data 
  22.      * @param parameterName 
  23.      * @param contentType 
  24.      */  
  25.     public FormFile(String filname, byte[] data, String parameterName, String contentType)   
  26.     {  
  27.         this.data = data;  
  28.         this.filname = filname;  
  29.         this.parameterName = parameterName;  
  30.         if(contentType!=nullthis.contentType = contentType;  
  31.     }  
  32.       
  33.     /** 
  34.      * 上傳大文件,一邊讀文件數據一邊上傳 
  35.      * @param filname 
  36.      * @param file 
  37.      * @param parameterName 
  38.      * @param contentType 
  39.      */  
  40.     public FormFile(String filname, File file, String parameterName, String contentType)   
  41.     {  
  42.         this.filname = filname;  
  43.         this.parameterName = parameterName;  
  44.         this.file = file;  
  45.         try   
  46.         {  
  47.             this.inStream = new FileInputStream(file);  
  48.         }  
  49.         catch (FileNotFoundException e)   
  50.         {  
  51.             e.printStackTrace();  
  52.         }  
  53.         if(contentType!=nullthis.contentType = contentType;  
  54.     }  
  55.       
  56.     public File getFile()   
  57.     {  
  58.         return file;  
  59.     }  
  60.     public InputStream getInStream()   
  61.     {  
  62.         return inStream;  
  63.     }  
  64.     public byte[] getData()   
  65.     {  
  66.         return data;  
  67.     }  
  68.     public String getFilname()   
  69.     {  
  70.         return filname;  
  71.     }  
  72.     public void setFilname(String filname)  
  73.     {  
  74.         this.filname = filname;  
  75.     }  
  76.     public String getParameterName()   
  77.     {  
  78.         return parameterName;  
  79.     }  
  80.     public void setParameterName(String parameterName)   
  81.     {  
  82.         this.parameterName = parameterName;  
  83.     }  
  84.     public String getContentType()  
  85.     {  
  86.         return contentType;  
  87.     }  
  88.     public void setContentType(String contentType)   
  89.     {  
  90.         this.contentType = contentType;  
  91.     }     
  92. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章