Android HTTP Communication--4.android HTTP request mode: HttpClient

Source: Internet
Author: User

Introduction to this section:

In the last section of the HttpURLConnection, this section to HttpClient, Apache to provide us with the HttpClient (simple HTTP client),
But after all, not a pro-son, httpclient after the API 21 version of Google deprecated, and we actually developed, many pages are not through
A simple URL can be accessed, may need to login or related permissions to access, which involves the session,cookie and so on;
Of course we can use httpurlconnection to achieve, but a little trouble, and with HttpClient can be simple point; HttpClient for receiving/sending
HTTP request/Response, but do not cache the server response, do not perform HTML page into the JS code, do not parse the content of the page, processing;
To get rid of the habit of too much nonsense, so simplify the blog, start this section:

HttpClient Use process:

Basic Flow:

HttpClient Use Example: 1. Send a GET request

Well, just write a simple code to send a GET request:

 PackageCom.example.httpclientdemo;Importorg.apache.http.HttpEntity;ImportOrg.apache.http.HttpResponse;ImportOrg.apache.http.client.HttpClient;ImportOrg.apache.http.client.methods.HttpGet;ImportOrg.apache.http.impl.client.DefaultHttpClient;ImportOrg.apache.http.util.EntityUtils;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.webkit.WebView;ImportAndroid.widget.Button; Public  class mainactivity extends Activity implements Onclicklistener  {    PrivateButton Btnget;PrivateWebView Wview; Public Static Final intShow_data =0X123;PrivateString detail ="";PrivateHandler Handler =NewHandler () { Public void Handlemessage(Message msg) {if(Msg.what = = Show_data) {Wview.loaddatawithbaseurl ("", detail,"Text/html","UTF-8","");    }        }; };@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        Initview ();    Setview (); }Private void Initview() {btnget = (Button) Findviewbyid (r.id.btnget);    Wview = (WebView) Findviewbyid (R.id.wview); }Private void Setview() {Btnget.setonclicklistener ( This); Wview.getsettings (). setdomstorageenabled (true); }@Override     Public void OnClick(View v) {if(V.getid () = = R.id.btnget)        {getbyhttpclient (); }    }Private void getbyhttpclient() {NewThread () { Public void Run()             {Try{HttpClient HttpClient =NewDefaulthttpclient (); HttpGet HttpGet =NewHttpGet ("Http://www.w3cschool.cc/python/python-tutorial.html"); HttpResponse HttpResponse = Httpclient.execute (HttpGet);if(Httpresponse.getstatusline (). Getstatuscode () = = $) {httpentity entity = httpresponse.getentity (); Detail = entityutils.tostring (Entity,"Utf-8");                        Handler.sendemptymessage (Show_data); }                    }Catch(Exception e)                    {E.printstacktrace ();        }            };    }.start (); }}

In addition, if it is a GET request with a parameter, we can put the parameter in the list collection and URL encode the parameter:
And then splice with the URL

List<Basicnamevaluepair> params = NewLinkedList<Basicnamevaluepair>();params.AddNewBasicnamevaluepair ("User","pig brother."));params.AddNewBasicnamevaluepair ("Pawd","123"));StringParam=Urlencodedutils.Formatparams,"UTF-8"); HttpGet HttpGet= NewHttpGet ("Http://www.baidu.com"+"?"+param);

Then post the run:

2. Send a POST request

The POST request is slightly more complex than get, and after the HttpPost object is created, the Namevaluepair collection is stored to wait for the commit
Parameters, and passes the parameters to urlencodedformentity, and finally calls Setentity (entity) to complete,
Httpclient.execute (HttpPost) can be, this is not to write an example, temporarily did not find the post site, and do not want to
Write yourself a servlet,so, directly paste the core code it ~

Core code:

    Private void postbyhttpclient(Final String URL) {NewThread () { Public void Run()             {Try{HttpClient HttpClient =NewDefaulthttpclient (); HttpPost HttpPost =NewHttpPost (URL); List<namevaluepair>params=NewArraylist<namevaluepair> ();params. Add (NewBasicnamevaluepair ("User","brother Pig."));params. Add (NewBasicnamevaluepair ("Pawd","123")); urlencodedformentity entity =NewUrlencodedformentity (params,"UTF-8");                    Httppost.setentity (entity); HttpResponse HttpResponse = Httpclient.execute (HttpPost);if(Httpresponse.getstatusline (). Getstatuscode () = = $) {httpentity entity2 = httpresponse.getentity (); Detail = entityutils.tostring (Entity2,"Utf-8");                    Handler.sendemptymessage (Show_data); }                }Catch(Exception e)            {E.printstacktrace ();}        };    }.start (); }
3. Nonsense

In fact, there are many examples of httpclient, such as the author used it to grasp the school teaching system on the student's timetable:
This involves the cookie, simulates the landing thing, when it comes to grasping data (reptiles), generally we are paired with Jsoup to parse
Catch the data, interested in the relevant information can be consulted, as for the author of the completion, the code is very rotten said, follow-up time
Finishing in the release, here paste the simulation of the educational system part of the code, we can experience the following httpclient:

//Get links to simulate login implementations:     Public int GetConnect(string user, String key) throws Exception {//Send GET request to get cookie value and __viewstate value firstHttpGet GetLogin =NewHttpGet (True_url);//First step: main HTML:String loginhtml =""; HttpResponse Loginresponse =NewDefaulthttpclient (). Execute (getlogin);if(Loginresponse.getstatusline (). Getstatuscode () = = $) {httpentity entity = loginresponse.getentity (); loginhtml = entityutils.tostring (entity);//Get the cookie value of the responseCookie = Loginresponse.getfirstheader ("Set-cookie"). GetValue (); System. out. println ("Cookie="+ cookies); }///Step Two: Analog login        //Send POST request, disable redirectionHttpPost HttpPost =NewHttpPost (True_url); Httppost.getparams (). Setparameter (Clientpnames.handle_redirects,false);//Set the parameters of the header information for post submissionHttppost.setheader ("User-agent","mozilla/5.0 (Windows NT 6.3; WOW64; trident/7.0; rv:11.0) like Gecko "); Httppost.setheader ("Referer", True_url); Httppost.setheader ("Cookie", cookies);//Set request dataList<namevaluepair>params=NewArraylist<namevaluepair> ();params. Add (NewBasicnamevaluepair ("__viewstate", Getviewstate (loginhtml)));//__viewstate parameter, if the change can be dynamically fetched        params. Add (NewBasicnamevaluepair ("Button1",""));params. Add (NewBasicnamevaluepair ("Hidpdrs",""));params. Add (NewBasicnamevaluepair ("HIDSC",""));params. Add (NewBasicnamevaluepair ("Lblanguage",""));params. Add (NewBasicnamevaluepair ("RadioButtonList1","%d1%a7%c9%fa"));params. Add (NewBasicnamevaluepair ("txtUserName", user));params. Add (NewBasicnamevaluepair ("TextBox2", key));params. Add (NewBasicnamevaluepair ("Txtsecretcode",""));//(╯-╰) Tease Square, unexpectedly do not need verification code        //Set the encoding method, respond to the request, get the response status code:Httppost.setentity (NewUrlencodedformentity (params,"gb2312")); HttpResponse response =NewDefaulthttpclient (). Execute (httppost);intStatus = Response.getstatusline (). Getstatuscode ();if(Status = = $)returnStatus; System. out. println ("status="+ Status);//Redirect Status code is 302        if(Status = =302|| Status = =301) {//Get the value of location in header informationLocation = Response.getfirstheader ("Location"). GetValue (); System. out. println (location);//Step three: Get the main page of management information            //Get requestHttpGet HttpGet =NewHttpGet (Ip_url + location);//With location accessHttpget.setheader ("Referer", True_url); Httpget.setheader ("Cookie", cookies);//HTML for home pagemainhtml =""; HttpResponse Httpresponseget =NewDefaulthttpclient (). Execute (httpget);if(Httpresponseget.getstatusline (). Getstatuscode () = = $) {httpentity entity = httpresponseget.getentity ();            mainhtml = entityutils.tostring (entity); }        }returnStatus; }
Summarize:

OK, this section about HttpClient here, the content is relatively simple ~
We will use retrofit to encapsulate our HTTP requests in the next section, so please look forward to

Android HTTP Communication--4.android HTTP request mode: HttpClient

Related Article

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.