码迷,mamicode.com
首页 > 移动开发 > 详细

Android 如何用HttpClient 以Post方式提交数据并添加http头信息

时间:2015-02-25 20:59:34      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

转自:http://www.linuxidc.com/Linux/2011-09/42772.htm

Android 如何 post json格式的数据,并附加http头,接受返回数据,请看下面的代码:

 1     private void HttpPostData() {
 2         try {
 3             HttpClient httpclient = new DefaultHttpClient();
 4             String uri = "http://www.yourweb.com";
 5             HttpPost httppost = new HttpPost(uri);
 6             // 添加http头信息
 7             httppost.addHeader("Authorization", "your token"); // 认证token
 8             httppost.addHeader("Content-Type", "application/json");
 9             httppost.addHeader("User-Agent", "imgfornote");
10             // http post的json数据格式: {"name": "your name","parentId":
11             // "id_of_parent"}
12             JSONObject obj = new JSONObject();
13             obj.put("name", "your name");
14             obj.put("parentId", "your parentid");
15             httppost.setEntity(new StringEntity(obj.toString()));
16             HttpResponse response;
17             response = httpclient.execute(httppost);
18             // 检验状态码,如果成功接收数据
19             int code = response.getStatusLine().getStatusCode();
20             if (code == 200) {
21                 String rev = EntityUtils.toString(response.getEntity());// 返回json格式:
22                                                                         // {"id":
23                                                                         // "27JpL~j4vsL0LX00E00005","version":
24                                                                         // "abc"}
25                 obj = new JSONObject(rev);
26                 String id = obj.getString("id");
27                 String version = obj.getString("version");
28             }
29         } catch (ClientProtocolException e) {
30         } catch (IOException e) {
31         } catch (Exception e) {
32         }
33     }

主要用到的类有:org.apache.http.client.HttpClient 、org.apache.http.client.methods.HttpPost 和 org.json.JSONObject

Android 如何用HttpClient 以Post方式提交数据并添加http头信息

标签:

原文地址:http://www.cnblogs.com/x_wukong/p/4300026.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!