Android Network Programming (3), android Network Programming

Source: Internet
Author: User

Android Network Programming (3), android Network Programming

Most Android apps Use HTTP to send and receive data. In Android development, two types of http clients are usually used: HttpClient of Apache and HttpURLConnection. Both HTTP client APIs support HTTPS protocol, stream data upload and download, configuration timeout, IPV6 protocol, and connection pool.

Apache HttpClient

HttpClient has a large number of APIs and has few bugs. However, the HttpClient API is relatively large, and it is difficult to extend it on the premise of ensuring compatibility. Therefore, many Android teams do not like it very much. HttpClient is an interface that encapsulates http requests, authentication, and connection management to be executed. There are three main implementation classes: AbstractHttpClient, AndroidHttpClient, and DefaultHttpClient. Next, let's take a look at AndroidHttpClient, which improves DefaultHttpClient to make it more suitable for Android development. Therefore, the steps for AndroidHttpClient to send requests and receive responses are as follows:

Generally, we do not perform network request operations in the main thread, but open a new sub-thread to perform network operations. The following code shows how to use AndroidHttpClient to complete the network login verification task:

Public class LoginTask implements Runnable {private String username; private String password; public LoginTask (String username, String password) {// initialize the user name and password this. username = username; this. password = password;} @ Override public void run () {// set the accessed Web site String path = "http: // xxxx/loginas. aspx "; // set the Http request parameter Map <String, String> params = new HashMap <String, String> (); params. put ("username", user Name); params. put ("password", password); String result = sendHttpClientPost (path, params, "UTF-8"); // output the returned interface to System. out. println (result );} /*** send an Http request to the Web site * @ param path Web site request address * @ param map Http Request Parameter * @ param encode encoding format * @ return Web site response string * /private String sendHttpClientPost (String path, map <String, String> map, String encode) {List <NameValuePair> list = new ArrayList <NameValuePair> (); if (Map! = Null &&! Map. isEmpty () {for (Map. entry <String, String> entry: map. entrySet () {// parse the parameters passed by Map and save it with a key value on the object BasicNameValuePair. List. add (new BasicNameValuePair (entry. getKey (), entry. getValue () ;}try {// encapsulate Request Parameters in HttpEntity. UrlEncodedFormEntity entity = new UrlEncodedFormEntity (list, encode); // use HttpPost to request HttpPost httpPost = new HttpPost (path); // Set Request Parameters to Form. HttpPost. setEntity (entity); // instantiate a default Http client that uses AndroidHttpClient HttpClient client = AndroidHttpClient. newInstance (""); // executes the request and obtains the response data HttpResponse httpResponse = client.exe cute (httpPost); // determines whether the request is successful. If it is set to 200, the request is successful, other questions are asked. If (httpResponse. getStatusLine (). getStatusCode () = 200) {// get the response stream InputStream inputStream = httpResponse through HttpEntity. getEntity (). getContent (); return changeInputStream (inputStream, encode) ;}} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (ClientProtocolException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (IOException E) {// TODO Auto-generated catch block e. printStackTrace ();} return "";} /*** convert the response flow returned by the Web site to the String format * @ param inputStream response stream * @ param encode encoding format * @ return converted String */private String changeInputStream (InputStream inputStream, string encode) {ByteArrayOutputStream outputStream = new ByteArrayOutputStream (); byte [] data = new byte [1024]; int len = 0; String result = ""; if (inputStream! = Null) {try {while (len = inputStream. read (data ))! =-1) {outputStream. write (data, 0, len);} result = new String (outputStream. toByteArray (), encode);} catch (IOException e) {e. printStackTrace () ;}} return result ;}}

 

HttpURLConnection

In contrast, HttpURLConnection is more common. It is a multi-purpose, lightweight HTTP client, applicable to most app clients. At the same time, HttpURLConnection is simple and easy to expand. However, some bugs exist in HttpURLConnection before Android2.2. For example, connection pool failure may occur when you try to disable InputStream. Therefore, we recommend that you use HttpURLConnection in Versions later than 2.3.

The following uses the request for the Baidu homepage logo as an example to demonstrate how to use the HttpURLConnection GET method to complete the network request task:

Public class getImageTask {private static String URL_PATH = http://www.baidu.com/img/bd_logo1.png;/*** @ param args */public static void main (String [] args) {// call the method to obtain the image and save the saveImageToDisk ();}/*** access the image through the URL of URL_PATH and save it to the local device */public static void saveImageToDisk () {InputStream inputStream = getInputStream (); byte [] data = new byte [1024]; int len = 0; FileOutputStream fileOutputStream = null; try {// Graph FileOutputStream = new FileOutputStream ("F: \ test.png"); while (len = inputStream. read (data ))! =-1) {// write the image stream fileOutputStream to the local file. write (data, 0, len) ;}} catch (IOException e) {e. printStackTrace ();} finally {// finally close the stream if (inputStream! = Null) {try {inputStream. close () ;}catch (IOException e) {e. printStackTrace () ;}} if (fileOutputStream! = Null) {try {fileOutputStream. close ();} catch (IOException e) {e. printStackTrace () ;}}}/ *** obtain the image input stream through the URL * @ return URL address. */Public static InputStream getInputStream () {InputStream inputStream = null; HttpURLConnection httpURLConnection = null; try {// instantiate a URL object based on the URL address to create an HttpURLConnection object. URL url = new URL (URL_PATH); if (url! = Null) {// openConnection obtains the connection httpURLConnection = (HttpURLConnection) URL of the current url. openConnection (); // set the response timeout for 3 seconds. setConnectTimeout (3000); // you can specify httpURLConnection. setDoInput (true); // set it to GET to request data httpURLConnection. setRequestMethod ("GET"); // GET the connection response code. The value 200 indicates that the connection is successful. If the value indicates that the connection is successful, int responseCode = httpURLConnection. getResponseCode (); if (responseCode = 200) {// getInputStream gets the data stream returned by the server. InputStream = httpURLConnection. getInputStream () ;}} catch (MalformedURLException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} return inputStream ;}}

If the POST method is used, you need to set the request parameters. Next we will use the POST method and HttpURLConnection to complete the same login verification function as above:

public class LoginTask implements Runnable{    private static String PATH = "http://xxxxx/loginas.aspx";    private static URL url;    private String username;
    private String password;
    public LoginTask(String username, String password) {
// Initialize the user name and password
        this.username = username; 
        this.password = password; 
}/*** Using the given Request Parameters and encoding format, obtain the data returned by the server * @ param params request parameter * @ param encode encoding format * @ return the String */public static String sendPostMessage (Map <String, String> params, String encode) {StringBuffer buffer = new StringBuffer (); if (params! = Null &&! Params. isEmpty () {for (Map. entry <String, String> entry: params. entrySet () {try {buffer. append (entry. getKey ()). append ("= "). append (URLEncoder. encode (entry. getValue (), encode )). append ("&"); // use & to separate request parameters.} Catch (UnsupportedEncodingException e) {e. printStackTrace () ;}} buffer. deleteCharAt (buffer. length ()-1); System. out. println (buffer. toString (); try {HttpURLConnection urlConnection = (HttpURLConnection) url. openConnection (); urlConnection. setConnectTimeout (3000); // set to allow the input and output of urlConnection. setDoInput (true); urlConnection. setDoOutput (true); byte [] mydata = buffer. toString (). getBytes (); // sets the request to report Set the request data type urlConnection. setRequestProperty ("Content-Type", "application/x-www-form-urlencoded"); // set the length of request data to urlConnection. setRequestProperty ("Content-Length", String. valueOf (mydata. length); // set the POST method to request data urlConnection. setRequestMethod ("POST"); OutputStream outputStream = urlConnection. getOutputStream (); outputStream. write (mydata); int responseCode = urlConnection. getResponseCode (); if (respons ECode = 200) {return changeInputStream (urlConnection. getInputStream (), encode) ;}} catch (IOException e) {e. printStackTrace () ;}} return "";} /*** convert the input stream returned by the server to the String format * @ param inputStream the input stream returned by the server * @ param encode encoding format * @ return parsed String */private static String changeInputStream (InputStream inputStream, string encode) {ByteArrayOutputStream outputStream = new ByteArrayOutputStream (); byte [] Data = new byte [1024]; int len = 0; String result = ""; if (inputStream! = Null) {try {while (len = inputStream. read (data ))! =-1) {outputStream. write (data, 0, len);} result = new String (outputStream. toByteArray (), encode);} catch (IOException e) {e. printStackTrace () ;}} return result ;}@ Override public void run () {// set the request string through Map.
        try { 
            url = new URL(PATH); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
                  Map<String, String> params = new HashMap<String, String>();        params.put("username", "admin");        params.put("password", "123");                String result=sendPostMessage(params, "utf-8");        System.out.println(result);    }}

 

 

Summary

Which client is better? Using httpClient before 2.2 can avoid some bugs. In Versions later than 2.3, using HttpURLConnection is the best choice. Simple APIs are suitable for Android development. Transparent compression and response data capture reduce network usage, improve performance, and reduce battery consumption.

In the open-source library we introduced later, volley used HttpClient in versions earlier than 2.3, while HttpURLConnection was used after 2.3; HttpClient was encapsulated in android-async-http.

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.