Transferred from: http://www.linuxidc.com/Linux/2011-09/42772.htm
For Android How to post JSON-formatted data and attach an HTTP header to accept the return data, see the following code:
1 Private voidHttppostdata () {2 Try {3HttpClient HttpClient =Newdefaulthttpclient ();4String uri = "http://www.yourweb.com";5HttpPost HttpPost =NewHttpPost (URI);6 //Add HTTP header information7Httppost.addheader ("Authorization", "Your Token");//Certified Tokens8Httppost.addheader ("Content-type", "Application/json");9Httppost.addheader ("User-agent", "Imgfornote");Ten //JSON data format for HTTP POST: {"name": "Your Name", "ParentID": One //"Id_of_parent"} AJsonobject obj =NewJsonobject (); -Obj.put ("name", "Your Name"); -Obj.put ("ParentID", "Your ParentID"); theHttppost.setentity (Newstringentity (obj.tostring ())); - HttpResponse response; -Response =Httpclient.execute (httppost); - //Verify the status code if the data is successfully received + intCode =response.getstatusline (). Getstatuscode (); - if(Code = = 200) { +String rev = entityutils.tostring (Response.getentity ());//returns the JSON format: A //{"id": at //"27jpl~j4vsl0lx00e00005", "Version": - //"abc"} -obj =NewJsonobject (rev.); -String id = obj.getstring ("id"); -String Version = obj.getstring ("Version"); - } in}Catch(clientprotocolexception e) { -}Catch(IOException e) { to}Catch(Exception e) { + } -}
The main classes used are: Org.apache.http.client.HttpClient, Org.apache.http.client.methods.HttpPost and Org.json.JSONObject
How Android uses httpclient to post data and add HTTP header information