Android HTTP POST上傳

來源:互聯網
上載者:User

標籤:android   style   c   class   blog   code   

HTTP POST上傳通用方法,支援文字、圖片、檔案等。

依賴jar包:http://hc.apache.org/downloads.cgi 下載HttpClient ***   Binary。

將HttpComponents libraries中的httpmime-4.3.3.jar拷貝到Android工程的libs下即可。

 

//填充上傳實體物件
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("String", new StringBody(“String”, Charset.forName("UTF-8")));entity.addPart("File", new FileBody(new File(“path”)));//調用post方法上傳
HttpTools.post("url", entity)//Http上傳通用方法類
public class HttpTools { public static final int HTTP_SUCCESS = 200; private static String response_string = null; private static JSONObject response_json = null;

  ......
  ......public static boolean post(String url, MultipartEntity entity) { try { HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpPost httpPost = new HttpPost(SERVER_ADDR + url); httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost, localContext); if (response.getStatusLine().getStatusCode() == HTTP_SUCCESS) { response_string = EntityUtils.toString(response.getEntity()); response_json = new JSONObject(response_string); return true; } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; }  ......
  ......}


關於上傳文字亂碼的情況說明:

之前沒有設定文字編碼

entity.addPart("String", new StringBody(“String”));

直接上傳文字就會亂碼。

在Android開發中,以HttpPost方式向伺服器上提交中文資料時,如果沒有設定傳輸資料的編碼類別型,在服務端擷取到的資料就會出現亂碼。在涉及不同平台上的應用,我們盡量使用UTF-8編碼格式傳輸中文資料,HttpPost方式傳輸中文指定編碼可以參考以下方法:

entity.addPart("String", new StringBody(“String”, Charset.forName("UTF-8")));

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.