Android 如何 post json格式的数据,并附加http头,接受返回数据,请看下面的代码:
- private void HttpPostData() {
- try {
- HttpClient httpclient = new DefaultHttpClient();
- String uri = "http://www.yourweb.com";
- HttpPost httppost = new HttpPost(uri);
-
- httppost.addHeader("Authorization", "your token");
- httppost.addHeader("Content-Type", "application/json");
- httppost.addHeader("User-Agent", "imgfornote");
-
- JSONObject obj = new JSONObject();
- obj.put("name", "your name");
- obj.put("parentId", "your parentid");
- httppost.setEntity(new StringEntity(obj.toString()));
- HttpResponse response;
- response = httpclient.execute(httppost);
-
- int code = response.getStatusLine().getStatusCode();
- if (code == 200) {
- String rev = EntityUtils.toString(response.getEntity());
- obj = new JSONObject(rev);
- String id = obj.getString("id");
- String version = obj.getString("version");
- }
- } catch (ClientProtocolException e) {
- } catch (IOException e) {
- } catch (Exception e) {
- }
- }
主要用到的类有:org.apache.http.client.HttpClient 、org.apache.http.client.methods.HttpPost 和 org.json.JSONObject