Android--apache HttpClient

Source: Internet
Author: User

The previous article describes the use of HttpURLConnection to complete support for the HTTP protocol. Now introduce a new way to access the Web site, that is httpclient.

HttpClient is an open source project provided by the Apache Open source organization, which is a simple HTTP client (not a browser) that can send HTTP requests to accept HTTP responses, as the name implies. But does not cache the server's response, cannot execute the HTTP page to check in the embedded JS code, naturally also does not have the page content to parse, the processing, these all need the developer to complete.

Now that Android has successfully integrated httpclient, developers can use HttpClient directly in Android projects to submit requests and accept responses to Web sites, and if other Java projects are used, they need to be introduced into the appropriate jar package. HttpClient can be downloaded on the official website.

  

HttpClient

HttpClient is actually a interface type, httpclient encapsulates the HTTP requests, authentication, connection management, and other features that an object needs to perform. From the document, HttpClient has three known implementation classes, namely: Abstracthttpclient, Androidhttpclient, Defaulthttpclient, There is an implementation class androidhttpclient that is specifically prepared for Android applications, and of course it can be implemented using regular defaulthttpclient, but since the Android app is being developed, or using Android's proprietary implementation class, there must be an advantage.

From the two Class pack all in position you can see the difference, Androidhttpclient is defined under the Android.net.http.AndroidHttpClient package and belongs to Android native HTTP access, while defaulthttpclient is defined in ORG.APACHE.HTTP.IMPL.CLI Ent. Under the Defaulthttpclient package, it belongs to the Apche project support. Androidhttpclient does not have a public constructor, only the static method Newinstance () method to obtain the Androidhttpclient object.

Androidhttpclient has made some improvements to defaulthttpclient to make it more useful for Android projects:

    1. Turn off expiration checks and self-connect can break all time limits.
    2. You can set ConnectionTimeout (connection timeout) and sotimeout (read data timeout).
    3. Turn off redirection.
    4. Use a session buffer for SSL Sockets.
    5. If the server is supported, use GZIP compression for data that is passed on the service side and the client.
    6. Cookies are not retained by default.

Simply speaking, sending a request with httpclient and receiving a response is simple and requires only a few steps:

    1. Creates a HttpClient object.
    2. Create the corresponding send Request object, create the HttpGet object if you need to send a GET request, and create a HttpPost object if you need to send a POST request.
    3. For the parameters that send the request, get and post use different ways, get method can use stitching string, the parameters are stitched at the end of the URL, the Post method needs to use the setentity (httpentity entity) method to set the request parameters.
    4. Calls the Execute (httpurirequest request) of the HttpClient object to send the request, and executes the method to return a HttpResponse object.
    5. Call HttpResponse's corresponding method to get the server's response header, response content, and so on.

Defaulthttpclient

First look at using the Defaulthttpclient method to send a Web site request, the above has briefly explained the steps, here is a brief description of a parameter transfer problem, for Get method, only need to stitch the string at the end of the URL, but for the post method, The Httpentity object needs to be passed, httpentity as an interface, with multiple implementation classes, with its indirect child inheritance, urlencodedformentity class to hold request parameters, and passed to HttpPost.

This example simple implementation of the Android client using the Defaulthttpclient implementation of an HTTP site landing implementation, using the post delivery, its delivery value only need to pass the Username+password, when the data passed to admin+ 123 thought the landing was successful. The Web site uses the. NET architecture, a generic handler, and a simple account password, which is not explained here.

Because of the special requirements for using the network after Android4.0, you can no longer access the network in the main thread, you must use the mode of multithreaded access, and some other information is described in the code comments.

Defaulthttpclient-code

  1 package com.bgxt.httpUtils;  2 3 Import Java.io.ByteArrayOutputStream;  4 Import java.io.IOException;  5 Import Java.io.InputStream;  6 Import java.io.UnsupportedEncodingException;  7 Import Java.util.ArrayList;  8 Import Java.util.HashMap; 9 Import java.util.List; Ten import Java.util.Map; Import Org.apache.http.HttpResponse; Import Org.apache.http.NameValuePair; Import org.apache.http.client.ClientProtocolException; Org.apache.http.client.entity.UrlEncodedFormEntity import; Org.apache.http.client.methods.HttpPost import; + Import org.apache.http.impl.client.DefaultHttpClient; Import Org.apache.http.message.BasicNameValuePair; public class Httpclientutils implements Runnable {21/** 22 * For environments above Android4.0, you cannot access the network in the main thread, so here's another new implementation The HTTP access class for the Runnable interface is * * */private String username; private String password; Httpclientutils Public (string Username, string password) {28//Initialize user name and password this.username = Username; This.password = password; () @Override the public void run () {35//Set the Web site visited. String Path = "http://192.168 .1.103:1231/loginas.ashx "; 37//Set HTTP request parameter map<string, string> params = new hashmap<string, string> (); Params.put ("username", username); Params.put ("password", password);          41 42string result = sendhttpclientpost (path, params, "utf-8");   43//Outputs the returned interface to SYSTEM.OUT.PRINTLN (result);  45} 46 47/** 48 * Send HTTP request to Web site * * @param path * * Web site request Address 52 * @param map * HTTP request parameter * @param encode 55 * Encoding format * * @return Web site response string $/sendhttpclientpost (string path, map<string, String> Map, and a-string Enco de) {list<namevaluepair> List = new arraylist<namevaluepair> (); if (map! = NULL &AMP;&A MP;!map.isempty ()) {map.entry<string, string> Entry:map.entrySet ()) {63// Parse the parameters of the map pass and save the object Basicnamevaluepair with a key value. List.add (New Basicnamevaluepair (Entry.getkey (), entry. GetValue ())); (+/-}): ({69///implementation) encapsulates the requested parameter encapsulation into the httpentity.            70urlencodedformentity entity = new Urlencodedformentity (list, encode);71//Use HttpPost request method HttpPost HttpPost = new HttpPost (path); 73//Set the request parameters into the form. 74httppost.setentity (entity); 75//Instantiate a default HTTP client, defaulthttpclient client = new Defaulthttpclient (); 77//Execute request and get response data of HttpResponse HttpResponse = Client.execute (HttpPost); 79//To determine if the request is successful, 200 to indicate success, others ask questions.                 if (Httpresponse.getstatusline (). Getstatuscode () = = 200) {81//Get response stream by Httpentity 82 InputStream InputStream = httpresponse.getentity (). getcontent (); Changeinputstream return (InputStream, encode); (Unsupportedencodingexception e) {e.printstacktrace (); CA             TCH (clientprotocolexception e) {e.printstacktrace (); (); catch (IOException e) {90 E.printstacktrace (); "";       93} 94 95/** 96 * Convert response stream returned by Web site to string format * 98 * @param inputstream 99 * Response Stream 100 * @param encode101 * encoding Format 102 * @returnConverted string 103 */104 private String Changeinputstream (InputStream InputStream, string encode) {Bytearrayo Utputstream outputstream = new Bytearrayoutputstream (); 106 byte[] data = new byte[1024];107 int len = 0;10 8 String result = ""; 109 if (inputstream! = null) {A-try {111 while (len =                 Inputstream.read (data))! =-1) {outputstream.write (data, 0, Len); 113}114                 result = new String (Outputstream.tobytearray (), encode); (IOException e) {117 E.printstacktrace (); 118}119}120 return result;121}122 123}

Androidhttpclient

The way of using androidhttpclient is similar to that of defaulthttpclient, but the few differences are explained above, but not in this example. One thing to note is that Androidhttpclient is a final class and there is no public constructor, so it cannot be instantiated with new, and must use Androidhttpclient.newinstance () method to get the Androidhttpclient object.

The example still uses the POST request, which implements the same functionality as the defaulthttpclient example. The details are already reflected in the comments and can be viewed directly from the code.

  1 package com.bgxt.httpUtils;  2 3 Import Java.io.ByteArrayOutputStream;  4 Import java.io.IOException;  5 Import Java.io.InputStream;  6 Import java.io.UnsupportedEncodingException;  7 Import Java.util.ArrayList;  8 Import Java.util.HashMap; 9 Import java.util.List; Ten import Java.util.Map; Import Org.apache.http.HttpResponse; Import Org.apache.http.NameValuePair; Import org.apache.http.client.ClientProtocolException; Org.apache.http.client.HttpClient import; Org.apache.http.client.entity.UrlEncodedFormEntity import; + Import Org.apache.http.client.methods.HttpPost; Import org.apache.http.impl.client.DefaultHttpClient; Import Org.apache.http.message.BasicNameValuePair; Import android.net.http.AndroidHttpClient;  The public class Androidhttpclientutils implements Runnable {for a private string username; Password    Androidhttpclientutils Public (string Username, string password) {29//Initialize user name and password 30     This.username = Username; This.password = password; () @Override () {36////Set the Web site that is accessed. PNS String path = "http://192.168 .1.103:1231/loginas.ashx "; 38//Set HTTP request parameters map<string, string> params = new hashmap<string, string> (); Params.put ("username", username); Params.put ("password", password); A. String result = sendhttpclientpost (path, params, "utf-8"); 44//Outputs the returned interface to SYSTEM.OUT.PRINTLN (result); 46} 47/** 48 * Send HTTP request to Web site * @param path Web site request address * @param map http request parameter * @para  m ENCODE encoded format * * @return Web site Response String * */Sendhttpclientpost (string path,map<string,          String> map,string encode) (list<namevaluepair> list=new arraylist<namevaluepair> (); 57 if (Map!=null&&!map.isempty ()) (Map.enTry<string, string> Entry:map.entrySet ()) 60 {61//parse Map pass parameters, use a key value pair object Basicnamevaluepa IR save. List.add (New Basicnamevaluepair (Entry.getkey (), Entry.getvalue ())); The "66" and "the" "try {+/////) Implementation encapsulates the requested parameter encapsulation into httpentity. Urlencodedformentity entity=new urlencodedformentity (list, encode); 68//Using HttpPost Request method HttpPost httppost=new HttpPost (path); 70//Set the request parameters into the form. Httppost.setentity (entity);  72//Instantiate a default HTTP client, using androidhttpclient HttpClient client=androidhttpclient.newinstance (""); 74//Execute request and get response data HttpResponse httpresponse= Client.execute (HttpPost); 76//To determine if the request is successful, 200 to indicate success, others ask questions. if (Httpresponse.getstatusline (). Getstatuscode () ==200) 78 {79//received via Httpentity Should flow InputStream Inputstream=httpresponse.getenTity (). getcontent (); Bayi return Changeinputstream (Inputstream,encode); (Unsupportedencodingexception e) {//TODO Auto-generat Ed Catch Block E.printstacktrace (); (Clientprotocolexception e) {//TODO auto-generated catch block e.prints Tacktrace ();  (IOException e) {//TODO auto-generated catch block E.printstacktrace (); "94"; 96} 97/** 98 * Convert response stream returned by Web site to string format * @param inputstream response stream * @param e             NCODE encoded Format 101 * @return converted string 102 */103 private String Changeinputstream (InputStream inputstream,104 String encode) {Bytearrayoutputstream outputstream = new Bytearrayoutputstream (); 106 byte[] Da TA = new byte[1024];107 int len = 0;108 String result=""; 109 if (inputstream! = null) {A-try {111 while (len = inputstream.read (data))! =                    -1) {outputstream.write (Data,0,len);             113}114 Result=new String (Outputstream.tobytearray (), encode); 115 116 } catch (IOException e) {117 e.printstacktrace (); 118}119}120 return result;121}122}

Android--apache HttpClient

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.