This section describes:
He talked about part of the httpurlconnection. This section httpclient, Apache provides us with httpclient (simple HTTP client), but is not a pro-son after all. HttpClient was deprecated by Google after the API 21 version number. And we are actually developing. Very many pages are not through a simple URL to be able to access, may need to login or the relevant authority to interview, 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. The httpclient is used to receive/send HTTP requests/responses. But does not cache the server response, does not perform the HTML page to infiltrate the JS code, does not carry on the page content no matter what parsing. To get rid of the habit of too much nonsense, so simplify the blog and start this section:
HttpClient Use process:
Basic Flow:
HttpClient using Demo sample: 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 (); }}
Other than that. Given a GET request with a number of parameters, we can put the number of references in the list collection and URL encode the parameters:
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 execution:
2. Send a POST request
The POST request is slightly more complicated than the get. After the HttpPost object is created, the Namevaluepair collection is stored to wait for the commit
The number of references. and passes the number of parameters to urlencodedformentity, and finally calls Setentity (entity) to complete,
Httpclient.execute (HttpPost) can. This is not the case. Temporarily did not find the post site, and do not want to
Write a servlet yourself. So, directly stick to the core code bar ~
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
There are actually a lot of examples of httpclient. For example, I used it to catch the student's timetable on the school administration system:
This involves cookies, simulating landing things, and talking about grabbing data (crawlers). Generally we are paired with Jsoup to analyze
If you get the data, you are interested in having access to the relevant documents. As for the author's completion, the code is very rotten to say. Maybe there's time.
Sort it out in the announcement. This is the code that simulates the part of the educational system. 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: basic 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 number of 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 parameters, assuming changes 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, actually do not need to verify the 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);//Bring the location address to the interviewHttpget.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 still relatively simple ~
We will use retrofit to encapsulate our HTTP requests in the next section. Please look forward to ~
By the right, the simple Web technology on Android can take you to the introductory series that the Piglet wrote before:
Piglet's Android starter Road Day 8 Part 3
Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.
Android HTTP Communication--4.android HTTP request information: HttpClient