標籤: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")));