Android-based Http Communication-4. Android HTTP Request Method: HttpClient
This section introduces:
In the previous section, we talked about HttpURLConnection. In this section, we will go to HttpClient, which is the HttpClient (simple Http client) provided by Apache ),
After all, HttpClient is not a parent-child. After API 21, HttpClient has been used up by Google. In actual development, many pages do not pass
A simple URL can be accessed, which may require logon or related permissions. This involves Session and Cookie issues;
Of course, we can use HttpURLConnection for implementation, but it is a little troublesome, but HttpClient can be simple; HttpClient is used for receiving/sending
Http Request/response, but does not Cache Server Response, does not execute JS Code that HTML pages sneak into, does not parse or process the page content;
To get rid of the habit of too much nonsense, SO simplify the blog and start with this section:
HttpClient usage process:
Basic Process:
HttpClient example: 1. Send a GET request
Well, write a simple code for sending GET requests:
package com.example.httpclientdemo;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.util.EntityUtils;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;import android.view.View.OnClickListener;import android.webkit.WebView;import android.widget.Button;public class MainActivity extends Activity implements OnClickListener { private Button btnGet; private WebView wView; public static final int SHOW_DATA = 0X123; private String detail = ""; private Handler handler = new Handler() { 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() { new Thread() { public void run() { try { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://www.w3cschool.cc/python/python-tutorial.html"); HttpResponse httpResponse = httpClient.execute(httpGet); if (httpResponse.getStatusLine().getStatusCode() == 200) { 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 parameters, we can put the parameters in the List set and perform URL encoding on the parameters:
Then splice with the URL
List
Params = new queue list
(); Params. add (new BasicNameValuePair ("user", ""); params. add (new BasicNameValuePair ("pawd", "123"); String param = URLEncodedUtils. format (params, "UTF-8"); HttpGet httpGet = new HttpGet ("http://www.baidu.com" + "? "+ Param );
Then paste and run:
2. Send a POST request
POST requests are a little more complex than GET requests. After an HttpPost object is created, the NameValuePair set is used to store the objects waiting for submission.
And pass the parameter to UrlEncodedFormEntity, and finally call setEntity (entity,
HttpClient.exe cute (HttpPost); I will not write an example here. I have not found the Post website yet and do not want
Write a Servlet and So by yourself. paste the core code directly ~
Core code:
Private void PostByHttpClient (final String url) {new Thread () {public void run () {try {HttpClient httpClient = new DefaultHttpClient (); HttpPost httpPost = new HttpPost (url); List
Params = new ArrayList
(); Params. add (new BasicNameValuePair ("user", ""); params. add (new BasicNameValuePair ("pawd", "123"); UrlEncodedFormEntity entity = new UrlEncodedFormEntity (params, "UTF-8"); httpPost. setEntity (entity); HttpResponse httpResponse = httpClient.exe cute (httpPost); if (httpResponse. getStatusLine (). getStatusCode () = 200) {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. For example, I used it to capture the curriculum of students in the school's educational administration system:
This involves cookies and simulated login. When it comes to data grabbing (crawling), we usually use JSoup to parse
If you are interested in capturing the data, you can check the relevant information on your own. As for my design, the code is very bad and there will be time in the future.
Sort it out and post it here to simulate the code used to log on to the educational administration system. You can understand HttpClient:
// Obtain the link and simulate Logon: public int getConnect (String user, String key) throws Exception {// first send a get request to obtain the cookie value and _ ViewState value HttpGet getLogin = new HttpGet (true_url); // Step 1: Main HTML: string loginhtml = ""; HttpResponse loginResponse = new defaulthttpclient(cmd.exe cute (getLogin); if (loginResponse. getStatusLine (). getStatusCode () = 200) {HttpEntity entity = loginResponse. getEntity (); loginhtml = EntityUtils. toString (entity); // obtain the response cookie value cookie = loginResponse. getFirstHeader ("Set-Cookie "). getValue (); System. out. println ("cookie =" + cookie);} // Step 2: Simulate logon // send a Post request, disable redirect HttpPost httpPost = new HttpPost (true_url); httpPost. getParams (). setParameter (ClientPNames. HANDLE_REDIRECTS, false); // sets the parameter httpPost for the header information submitted by Post. 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", cookie); // sets the request data List
Params = new ArrayList
(); Params. add (new BasicNameValuePair ("_ VIEWSTATE", getViewState (loginhtml); // _ VIEWSTATE parameter. If the parameter changes, you can dynamically capture and obtain params. add (new BasicNameValuePair ("Button1", ""); params. add (new BasicNameValuePair ("hidPdrs", ""); params. add (new BasicNameValuePair ("hidsc", ""); params. add (new BasicNameValuePair ("lbLanguage", ""); params. add (new BasicNameValuePair ("RadioButtonList1", "% D1 % A7 % C9 % FA"); params. add (new BasicNameValuePair ("txtUserName", user); params. add (new BasicNameValuePair ("TextBox2", key); params. add (new BasicNameValuePair ("txtSecretCode", ""); // (encoding □encoding) tease ratio square, actually do not need the verification code // set the encoding method, respond to the request, get response status code: httpPost. setEntity (new UrlEncodedFormEntity (params, "gb2312"); HttpResponse response = new defaulthttpclient(cmd.exe cute (httpPost); int Status = response. getStatusLine (). getStatusCode (); if (Status = 200) return Status; System. out. println ("Status =" + Status); // The redirect Status code is 302 if (Status = 302 | Status = 301) {// obtain the Location Value in the header information location = response. getFirstHeader ("Location "). getValue (); System. out. println (location); // Step 3: Obtain the home page of the Management Information // Get request HttpGet httpGet = new HttpGet (ip_url + location); // access httpGet with the location address. setHeader ("Referer", true_url); httpGet. setHeader ("Cookie", cookie); // html mainhtml = ""; HttpResponse httpResponseget = new DefaultHttpClient (). execute (httpGet); if (httpResponseget. getStatusLine (). getStatusCode () = 200) {HttpEntity entity = httpResponseget. getEntity (); mainhtml = EntityUtils. toString (entity) ;}} return Status ;}
Summary:
Okay. Now let's take a look at HttpClient. The content is quite simple ~
In the next section, we will use dynamic fit to encapsulate our HTTP requests ~
By the way, for Simple Network Technology in Android, refer to the entry series written by pig before: