Android HttpClient上傳文件與Httpconnection知識小結

 Android上傳文件到服務端能夠使用HttpConnection 上傳文件,也能夠使用Android封裝好的HttpClient類。當僅僅上傳文件能夠直接使用httpconnection 上傳比較方便快捷。php

 

        一、使用HttpConection上傳文件。將文件轉換成表單數據流。主要的思路就本身構造個http協議內容,服務端解析報文得到表單數據。代碼片斷:java

 

[java] view plaincopyandroid

HttpURLConnection con;  apache

    try {  瀏覽器

        con = (HttpURLConnection) url.openConnection();  服務器

        con.setConnectTimeout(C_TimeOut);  post

        /* 容許Input、Output,不使用Cache */  url

        con.setDoInput(true);  spa

        con.setDoOutput(true);  .net

        con.setUseCaches(false);  

        /* 設置傳送的method=POST */  

        con.setRequestMethod("POST");  

        /* setRequestProperty */  

        con.setRequestProperty("Connection", "Keep-Alive");  

        con.setRequestProperty("Charset", "UTF-8");  

        con.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);  

      

        /* 設置DataOutputStream */  

         DataOutputStream ds = new DataOutputStream(con.getOutputStream());  

         FileInputStream fStream = new FileInputStream(file);  

  

          /* 設置每次寫入1024bytes */  

          int bufferSize = 1024;  

          byte[] buffer = new byte[bufferSize];  

  

          int length = -1;  

          /* 從文件讀取數據至緩衝區 */  

          while((length = fStream.read(buffer)) != -1)  

          {  

            /* 將資料寫入DataOutputStream中 */  

            ds.write(buffer, 0, length);  

          }   

          fStream.close();   

          ds.flush();  

          ds.close();  

           

 

能夠參考

 

        ①《在 Android 上經過模擬 HTTP multipart/form-data 請求協議信息實現圖片上傳》     (http://bertlee.iteye.com/blog/1134576)。

 

        ②《關於android Http訪問,上傳,用了三個方法 》

 

二、使用Android HttpClient類上傳參數。下面我在網上搜到得代碼,忘記出處了

 

   

 

[java] view plaincopy

private static boolean sendPOSTRequestHttpClient(String path,  

        Map<String, String> params) throws Exception {  

    // 封裝請求參數  

    List<NameValuePair> pair = new ArrayList<NameValuePair>();  

    if (params != null && !params.isEmpty()) {  

        for (Map.Entry<String, String> entry : params.entrySet()) {  

            pair.add(new BasicNameValuePair(entry.getKey(), entry  

                    .getValue()));  

        }  

    }   

    // 把請求參數變成請求體部分  

    UrlEncodedFormEntity uee = new UrlEncodedFormEntity(pair, "utf-8");   

    // 使用HttpPost對象設置發送的URL路徑  

    HttpPost post = new HttpPost(path);   

    // 發送請求體  

    post.setEntity(uee);   

    // 建立一個瀏覽器對象,以把POST對象向服務器發送,並返回響應消息  

    DefaultHttpClient dhc = new DefaultHttpClient();  

    HttpResponse response = dhc.execute(post);  

    if (response.getStatusLine().getStatusCode() == 200) {  

        Log.i("http", "httpclient");  

        return true;  

    }  

    return false;  

}  

 

三、使用httpClient上傳文字信息和文件信息。使用httpClient上傳文件很是的方便。不過須要導入apache-mime4j-0.6.jar 和httpmime-4.0.jar兩個.jar包。

 

[java] view plaincopy

// 封裝請求參數  

        MultipartEntity mpEntity = new MultipartEntity();  

        if (params != null && !params.isEmpty()) {  

            for (Map.Entry<String, String> entry : params.entrySet()) {  

  

                StringBody par = new StringBody(entry.getValue());  

                mpEntity.addPart(entry.getKey(), par);  

            }  

        }  

        // 圖片  

        if (!imagepath.equals("")) {  

            FileBody file = new FileBody(new File(imagepath));  

            mpEntity.addPart("photo", file);  

        }  

        // 使用HttpPost對象設置發送的URL路徑  

        HttpPost post = new HttpPost(path);  

        // 發送請求體  

        post.setEntity(mpEntity);  

        // 建立一個瀏覽器對象,以把POST對象向服務器發送,並返回響應消息  

        DefaultHttpClient dhc = new DefaultHttpClient();  

        HttpResponse response = dhc.execute(post);  

 

 

FileBody類能夠把文件封裝到表單中,實現附件的上傳。  

 

關於httpClient上傳文件能夠參考連接: http://www.eoeandroid.com/forum.php?mod=viewthread&tid=76721&page=1

 

須要用的的ja下載地址r:http://download.csdn.net/detail/china1988s/3791514

相關文章
相關標籤/搜索