Android using HttpClient method and error-prone problem

Source: Internet
Author: User
Tags response code

HttpClient provides Android developers with a simple way to operate HTTP network connections, there are two ways to connect, get and post, first look at how to implement the

The default is Get mode

//first put parameters into list  , and then URL-encode the parameter list<basicnamevaluepair> params = new linkedlist<basicnamevaluepair> ();  Params.add (New Basicnamevaluepair ("param1", "China"));  Params.add (New Basicnamevaluepair ("param2", "value2"));    BASEURL String baseUrl = "http://www.baidu.com";                Stitching the URL and parameters httpget GetMethod = new HttpGet (BaseUrl + "?" + param);    HttpClient HttpClient = new Defaulthttpclient (); try {httpresponse response = Httpclient.execute (GetMethod);//Initiate GET request LOG.I (TAG, "Rescode =" + response.gets Tatusline (). Getstatuscode ()); Get the response code LOG.I (TAG, "result =" + entityutils.tostring (response.getentity (), "Utf-8"));//Get server response content} catch (Clientpro  Tocolexception e) {//TODO auto-generated catch block E.printstacktrace ();  } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); }  


Post mode

In the same way as GET, the parameter is first placed in the list params = new linkedlist<basicnamevaluepair> ();  Params.add (New Basicnamevaluepair ("param1", "POST Method"));                Params.add (New Basicnamevaluepair ("Param2", "second parameter"));      try {httppost Postmethod = new HttpPost (BASEURL); Postmethod.setentity (New urlencodedformentity (params, "utf-8")); Fill in the parameters into post entity httpresponse response = Httpclient.execute (Postmethod); Execute the Post method log.i (TAG, "Rescode =" + Response.getstatusline (). Getstatuscode ()); Get the response code LOG.I (TAG, "result =" + entityutils.tostring (response.getentity (), "Utf-8")); Get response content} catch (Unsupportedencodingexception e) {//TODO auto-generated catch block E.prin  Tstacktrace ();  } catch (Clientprotocolexception e) {//TODO auto-generated catch block E.printstacktrace ();  } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); }
If you need to update the UI after you get the network resources, you need to use async, otherwise an error will occur

Handler Handler = new Handler () {@Override public void Handlemessage (Message msg) {if (msg.what            = = 0x123) {tv.settext (result);    }        }    };        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        TV = (TextView) Findviewbyid (r.id.tv);        result = "";        Final HttpClient HttpClient = new Defaulthttpclient (); New Thread () {public void run () {HttpGet HttpRequest = new HttpGet ("HT                Tp://www.baidu.com ");                    try {HttpResponse HttpResponse = Httpclient.execute (HttpRequest);                        if (Httpresponse.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK) {//Get the returned string                                              result = Entityutils.tostring (httpresponse.getentity ()); Tv.settext(result);//If you use it here you will get an error message msg = new Message ();                       Msg.what = 0x123;                    Handler.sendmessage (msg);                    }} catch (Clientprotocolexception e) {//TODO auto-generated catch block                E.printstacktrace ();                } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();        }}}.start (); }




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.