欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android基于Http協(xié)議實(shí)現(xiàn)文件上傳功能的方法

 更新時(shí)間:2016年07月06日 09:28:21   作者:與時(shí)俱進(jìn)  
這篇文章主要介紹了Android基于Http協(xié)議實(shí)現(xiàn)文件上傳功能的方法,結(jié)合實(shí)例形式分析了Android的HTTP協(xié)議原理與文件上傳功能實(shí)現(xiàn)技巧,需要的朋友可以參考下

本文實(shí)例講述了Android基于Http協(xié)議實(shí)現(xiàn)文件上傳功能的方法。分享給大家供大家參考,具體如下:

注意一般使用Http協(xié)議上傳的文件都比較小,一般是小于2M

這里示例是上傳一個(gè)小的MP3文件

1.主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);
    //提交上傳按鈕
    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
        {
          //得到SDCard的目錄
          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());
        }
      }
    });
  }
}

2.上傳工具類,注意里面構(gòu)造協(xié)議字符串需要根據(jù)不同的提交表單來處理

public class SocketHttpRequester
{
  /**
   * 發(fā)送xml數(shù)據(jù)
   * @param path 請(qǐng)求地址
   * @param xml xml數(shù)據(jù)
   * @param 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;
  }
  /**
   * 直接通過HTTP協(xié)議提交數(shù)據(jù)到服務(wù)器,實(shí)現(xiàn)如下面表單提交功能:
   *  <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" NAME="id">
      <input type="file" name="imagefile"/>
      <input type="file" name="zip"/>
     </FORM>
   * @param path 上傳路徑(注:避免使用localhost或127.0.0.1這樣的路徑測(cè)試,
   *         因?yàn)樗鼤?huì)指向手機(jī)模擬器,你可以使用http://www.baidu.com或http://192.168.1.10:8080這樣的路徑測(cè)試)
   * @param params 請(qǐng)求參數(shù) key為參數(shù)名,value為參數(shù)值
   * @param file 上傳文件
   */
  public static boolean post(String path, Map<String, String> params, FormFile[] files) throws Exception
  {
    //數(shù)據(jù)分隔線
    final String BOUNDARY = "---------------------------7da2137580612";
    //數(shù)據(jù)結(jié)束標(biāo)志"---------------------------7da2137580612--"
    final String endline = "--" + BOUNDARY + "--/r/n";
    //下面兩個(gè)for循環(huán)都是為了得到數(shù)據(jù)長度參數(shù),依據(jù)表單的類型而定
    //首先得到文件類型數(shù)據(jù)的總長度(包括文件分割線)
    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;
      }
    }
    //再構(gòu)造文本類型參數(shù)的實(shí)體數(shù)據(jù)
    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");
    }
    //計(jì)算傳輸給服務(wù)器的實(shí)體數(shù)據(jù)總長度(文本總長度+數(shù)據(jù)總長度+分隔符)
    int dataLength = textEntity.toString().getBytes().length + fileDataLength + endline.getBytes().length;
    URL url = new URL(path);
    //默認(rèn)端口號(hào)其實(shí)可以不寫
    int port = url.getPort()==-1 ? 80 : url.getPort();
    //建立一個(gè)Socket鏈接
    Socket socket = new Socket(InetAddress.getByName(url.getHost()), port);
    //獲得一個(gè)輸出流(從Android流到web)
    OutputStream outStream = socket.getOutputStream();
    //下面完成HTTP請(qǐng)求頭的發(fā)送
    String requestmethod = "POST "+ url.getPath()+" HTTP/1.1/r/n";
    outStream.write(requestmethod.getBytes());
    //構(gòu)建accept
    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());
    //構(gòu)建language
    String language = "Accept-Language: zh-CN/r/n";
    outStream.write(language.getBytes());
    //構(gòu)建contenttype
    String contenttype = "Content-Type: multipart/form-data; boundary="+ BOUNDARY+ "/r/n";
    outStream.write(contenttype.getBytes());
    //構(gòu)建contentlength
    String contentlength = "Content-Length: "+ dataLength + "/r/n";
    outStream.write(contentlength.getBytes());
    //構(gòu)建alive
    String alive = "Connection: Keep-Alive/r/n";
    outStream.write(alive.getBytes());
    //構(gòu)建host
    String host = "Host: "+ url.getHost() +":"+ port +"/r/n";
    outStream.write(host.getBytes());
    //寫完HTTP請(qǐng)求頭后根據(jù)HTTP協(xié)議再寫一個(gè)回車換行
    outStream.write("/r/n".getBytes());
    //把所有文本類型的實(shí)體數(shù)據(jù)發(fā)送出來
    outStream.write(textEntity.toString().getBytes());
    //把所有文件類型的實(shí)體數(shù)據(jù)發(fā)送出來
    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());
    }
    //下面發(fā)送數(shù)據(jù)結(jié)束標(biāo)志,表示數(shù)據(jù)已經(jīng)結(jié)束
    outStream.write(endline.getBytes());
    BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    //讀取web服務(wù)器返回的數(shù)據(jù),判斷請(qǐng)求碼是否為200,如果不是200,代表請(qǐng)求失敗
    if(reader.readLine().indexOf("200")==-1)
    {
      return false;
    }
    outStream.flush();
    outStream.close();
    reader.close();
    socket.close();
    return true;
  }
  /**
   * 提交數(shù)據(jù)到服務(wù)器
   * @param path 上傳路徑(注:避免使用localhost或127.0.0.1這樣的路徑測(cè)試,因?yàn)樗鼤?huì)指向手機(jī)模擬器,你可以使用http://www.baidu.com或http://192.168.1.10:8080這樣的路徑測(cè)試)
   * @param params 請(qǐng)求參數(shù) key為參數(shù)名,value為參數(shù)值
   * @param file 上傳文件
   */
  public static boolean post(String path, Map<String, String> params, FormFile file) throws Exception
  {
    return post(path, params, new FormFile[]{file});
  }
  /**
   * 提交數(shù)據(jù)到服務(wù)器
   * @param path 上傳路徑(注:避免使用localhost或127.0.0.1這樣的路徑測(cè)試,因?yàn)樗鼤?huì)指向手機(jī)模擬器,你可以使用http://www.baidu.com或http://192.168.1.10:8080這樣的路徑測(cè)試)
   * @param params 請(qǐng)求參數(shù) key為參數(shù)名,value為參數(shù)值
   * @param encode 編碼
   */
  public static byte[] postFromHttpClient(String path, Map<String, String> params, String encode) throws Exception
  {
    //用于存放請(qǐng)求參數(shù)
    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    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();
    //發(fā)送post請(qǐng)求
    HttpResponse response = httpclient.execute(httppost);
    return readStream(response.getEntity().getContent());
  }
  /**
   * 發(fā)送請(qǐng)求
   * @param path 請(qǐng)求路徑
   * @param params 請(qǐng)求參數(shù) key為參數(shù)名稱 value為參數(shù)值
   * @param encode 請(qǐng)求參數(shù)的編碼
   */
  public static byte[] post(String path, Map<String, String> params, String encode) throws Exception
  {
    //String params = "method=save&name="+ URLEncoder.encode("老畢", "UTF-8")+ "&age=28&";//需要發(fā)送的參數(shù)
    StringBuilder parambuilder = 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();
    //設(shè)置允許對(duì)外發(fā)送請(qǐng)求參數(shù)
    conn.setDoOutput(true);
    //設(shè)置不進(jìn)行緩存
    conn.setUseCaches(false);
    conn.setConnectTimeout(5 * 1000);
    conn.setRequestMethod("POST");
    //下面設(shè)置http請(qǐng)求頭
    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");
    //發(fā)送參數(shù)
    DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
    outStream.write(data);//把參數(shù)發(fā)送出去
    outStream.flush();
    outStream.close();
    if(conn.getResponseCode()==200)
    {
      return readStream(conn.getInputStream());
    }
    return null;
  }
  /**
   * 讀取流
   * @param inStream
   * @return 字節(jié)數(shù)組
   * @throws Exception
   */
  public static byte[] readStream(InputStream 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
{
  /**
   * 從輸入流讀取數(shù)據(jù)
   * @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();
  }
}
/**
 * 使用JavaBean封裝上傳文件數(shù)據(jù)
 *
 */
public class FormFile
{
  //上傳文件的數(shù)據(jù)
  private byte[] data;
  private InputStream inStream;
  private File file;
  //文件名稱
  private String filname;
  //請(qǐng)求參數(shù)名稱
  private String parameterName;
  //內(nèi)容類型
  private String contentType = "application/octet-stream";
  /**
   * 上傳小文件,把文件數(shù)據(jù)先讀入內(nèi)存
   * @param filname
   * @param data
   * @param parameterName
   * @param contentType
   */
  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;
  }
  /**
   * 上傳大文件,一邊讀文件數(shù)據(jù)一邊上傳
   * @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;
  }
  public 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;
  }
}

更多關(guān)于Android相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Android文件操作技巧匯總》、《Android操作SQLite數(shù)據(jù)庫技巧總結(jié)》、《Android操作json格式數(shù)據(jù)技巧總結(jié)》、《Android數(shù)據(jù)庫操作技巧總結(jié)》、《Android編程之a(chǎn)ctivity操作技巧總結(jié)》、《Android編程開發(fā)之SD卡操作方法匯總》、《Android開發(fā)入門與進(jìn)階教程》、《Android資源操作技巧匯總》、《Android視圖View技巧總結(jié)》及《Android控件用法總結(jié)

希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論