标签: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")));
Android HTTP POST上传,布布扣,bubuko.com
标签:android style c class blog code
原文地址:http://www.cnblogs.com/x-dev/p/android_http_post.html