7.1.4 Android HTTP Request Method: HttpClient
Category Android Basic Tutorial
Introduction to This Section:
>
In the previous section, we studied HttpURLConnection. This section introduces the second method: HttpClient. Although it has been deprecated by Google, we can still use HttpClient for packet capturing, and it works even better with Jsoup for parsing web pages! HttpClient is used for receiving/sending HTTP requests/responses, but it does not cache server responses, does not execute JS code embedded in HTML pages, and does not perform any parsing or processing of page content! Let's start with the content of this section!
1. HttpClient Usage Process
Basic Process :
2. HttpClient Usage Example
1) Sending GET Request with HttpClient
Here is a simple code snippet for sending a GET request:
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();
}
}
Screenshot of Running
Additionally, for a GET request with parameters, we can put the parameters into a List collection, URL-encode the parameters, and then concatenate them with the URL:
List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("user", "Pig Younger Brother"));
params.add(new BasicNameValuePair("pawd", "123"));
String param = URLEncodedUtils.format(params, "UTF-8");
HttpGet httpGet = new HttpGet("http://www.baidu.com"+"?"+param);
2) Sending POST Request with HttpClient
>
The POST request is slightly more complex than the GET request. After creating the HttpPost object, store the parameters to be submitted in a NameValuePair collection, pass the parameters to UrlEncodedFormEntity, and finally call setEntity(entity) to complete it. HttpClient.execute(HttpPost) can be done; I won't provide an example here, as I haven't found a website for Post, and I don't want to write a Servlet myself. So, I'll just post 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<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user", "Pig Big Brother"));
params.add(new BasicNameValuePair("pawd", "123"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,"UTF-8");
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(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. HttpClient Data Capture Example (Academic Affairs System Data Capture)
>
In fact, there HttpPost httpPost = new HttpPost(true_url); httpPost.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);
// Set the header information parameters for the POST submission httpPost.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);
// Set the request data List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("__VIEWSTATE", getViewState(loginhtml)));// __VIEWSTATE parameter, if it changes, it can be dynamically captured and obtained 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", "")); // (╯□╰) Foolish square, it turns out that there is no need for a verification code
// Set the encoding method, respond to the request, and obtain the response status code: httpPost.setEntity(new UrlEncodedFormEntity(params, "gb2312")); HttpResponse response = new DefaultHttpClient().execute(httpPost); int Status = response.getStatusLine().getStatusCode(); if(Status == 200)return Status; System.out.println("Status= " + Status);
// Redirect status code is 302 if (Status == 302 || Status == 301) { // Get the value of Location in the header information location = response.getFirstHeader("Location").getValue(); System.out.println(location); // Step three: Get the main page of the management information // Get request HttpGet httpGet = new HttpGet(ip_url + location); // Access with the location address httpGet.setHeader("Referer", true_url); httpGet.setHeader("Cookie", cookie);
// The main page's HTML
mainhtml = "";
HttpResponse httpResponseget = new DefaultHttpClient()
.execute(httpGet);
if (httpResponseget.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = httpResponseget.getEntity();
mainhtml = EntityUtils.toString(entity);
}
} return Status; }
4. Use HttpPut to send a PUT request
Example code is as follows :
public static int PutActCode(String actCode, String licPlate, Context mContext) {
int resp = 0;
String cookie = (String) SPUtils.get(mContext, "session", "");
HttpPut httpPut = new HttpPut(PUTACKCODE_URL);
httpPut.setHeader("Cookie", cookie);
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("activation_code", actCode));
params.add(new BasicNameValuePair("license_plate", licPlate));
httpPut.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse course_response = new DefaultHttpClient().execute(httpPut);
if (course_response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity2 = course_response.getEntity();
JSONObject jObject = new JSONObject(EntityUtils.toString(entity2));
resp = Integer.parseInt(jObject.getString("status_code"));
return resp;
}
} catch (Exception e) {
e.printStackTrace();
}
return resp;
}
Summary of this section:
>
Well, this section on the second request method for Android HTTP: HttpClient is over, starting next section, we will learn about XML and Json parsing, this section is over, thank you~
-1.0 Android Basic Tutorial Introduction
-1.0.1 Latest Android Basic Tutorial Catalog for 2015
-1.1 Background and System Architecture Analysis
-1.2 Development Environment Setup
-1.2.1 Developing Android APP with Eclipse + ADT + SDK
-1.2.2 Developing Android APP with Android Studio
-1.3 Solving SDK Update Issues
-1.4 Genymotion Emulator Installation
-[1.5.1 Git Tutorial on Basic Operations of
3.6 Responding to System Setting Events (Configuration Class)
4.4.2 Further Exploration of ContentProvider - Document Provider
[5.2.1 In-depth Explanation of Fragment - Implementation of Bottom Navigation Bar (Method
8.3.4 Paint API - Detailed Explanation of Xfermode and PorterDuff (Part 1)
8.3.5 Paint API - Detailed Explanation of Xfermode and PorterDuff (Part 2)
8.3.6 Paint API - Detailed Explanation of Xfermode and PorterDuff (Part 3)
8.3.7 Paint API - Detailed Explanation of Xfermode and PorterDuff (Part 4)
8.3.8 Paint API - Detailed Explanation of Xfermode and PorterDuff (Part 5)
8.3.14 Paint API - Several Enumerations/Constants and ShadowLayer Shadow Effect
8.3.17 Detailed Explanation of Canvas API (Part 2) - Collection of Clipping Methods
8.3.18 Detailed Explanation of Canvas API (Part 3) - Matrix and drawBitmapMesh
8.4.3 Android Animation Collection - Property Animation - First Encounter
8.4.4 Android Animation Collection - Property Animation - Re-encounter
[10.9 WallpaperManager (Wallpaper Manager)](android