How Android uses httpclient to post data and add HTTP header information

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.