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

转自: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

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。