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