Android HttpClient上傳檔案與Httpconnection知識小結

來源:互聯網
上載者:User

 Android上傳檔案到服務端可以使用HttpConnection 上傳檔案,也可以使用Android封裝好的HttpClient類。當僅僅上傳檔案可以直接使用httpconnection 上傳比較方便快捷。

 

        1、使用HttpConection上傳檔案。將檔案轉換成表單資料流。主要的思路就自己構造個http協議內容,服務端解析報文獲得表單資料。程式碼片段:

 

[java]

HttpURLConnection con; 

    try { 

        con = (HttpURLConnection) url.openConnection(); 

        con.setConnectTimeout(C_TimeOut); 

        /* 允許Input、Output,不使用Cache */ 

        con.setDoInput(true); 

        con.setDoOutput(true); 

        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 請求協議資訊實現圖片上傳》             ②《關於android Http訪問,上傳,用了三個方法 》

 

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

 

  

 

[java] 

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; 

} 

 

3、使用httpClient上傳文字資訊和檔案資訊。使用httpClient上傳檔案非常的方便。不過需要匯入apache-mime4j-0.6.jar 和httpmime-4.0.jar兩個.jar包。

 

[java] 

// 封裝請求參數 

        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類可以把檔案封裝到表單中,實現附件的上傳。 

 作者:安客成

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.