Android HTTP Network programming (i)

Source: Internet
Author: User

Android Application as a client program most of the need for network requests and access, and HTTP communication is a more common and common means of communication.

There are two implementations of HTTP network programming in Android, one using HttpURLConnection and the other using HttpClient.

The general process of these two implementations is as follows:

    1. The Android client makes a request to the server.
    2. The server receives the request and responds.
    3. The server returns data to the client.

In the HTTP communication there are two ways of post and get, the difference is that the Get method can get static pages, while the request parameters can be placed behind the URL string, passed to the server, and the post mode parameters are placed in the HTTP request. Therefore, regardless of which HTTP implementation you are using, you need to specify how you want to use the request.

Let's start by knowing HttpURLConnection:

HttpURLConnection inherit from the URLConnection class, both of which are abstract classes. The object is created primarily through the OpenConnection method of the URL object, and after acquiring the HttpURLConnection object, the default is to request the data by a Get method, where the input stream can be used to read the information.

Examples are as follows: (where strURL is "http://www.baidu.com")

Private HttpURLConnection Conn;

 URL url = new   URL (strurl); conn  =< Span style= "color: #000000;" > (HttpURLConnection) url.openconnection (); Conn.setrequestmethod ( "GET"); //  set request mode  Conn.setconnecttimeout (6 * 1000); //  conn.setreadtimeout (8000); //  if  (Conn.getresponsecode ()! = 200) //           throw  new  RuntimeException ("Run exception"  //  get the input stream returned by the server  InputStream is = Conn.getinputstream (); 

If you use post, you will also need to set some parameters (including some of the settings in the example above, as well as the following common settings).

Conn.setconnecttimeout (6 * 1000);//set the time when the connection timed outConn.setreadtimeout (8000);//set the number of milliseconds to read timeoutConn.setdooutput (true);//whether to allow outputConn.setusecaches (false);//whether to use the cacheConn.setrequestmethod ("POST");//Set Request ModeConn.setinstancefollowredirects (true);//whether to automatically perform HTTP redirection//The following settings are general request properties, that is, header information for Web pagesConn.setrequestproperty ("Charset", "UTF-8"); Conn.setrequestproperty ("Connection", "keep-alive"); Conn.setrequestproperty ("Content-type", "application/x-www-from-urlencoded"); Conn.setrequestproperty ("Content-length", String.valueof (Data.length));

HttpURLConnection depending on the purpose of use, the specific use will be slightly different. Below, a few examples of common applications are illustrated.

    1. Gets a Web page from the Internet, which sends a request to the URL and reads the Web page back to the local stream.
    2. Get files from the Internet, which is the use of HttpURLConnection objects to get file data from the network.
    3. Sends a request parameter to the Internet, that is, passing parameters to the server, that is, passing parameters to the server.
    4. Transfer XML data to the Internet. (The way to transfer files using HTTP, the general file size of 5M, HTTP communication is not suitable for transferring large files, the transmission of large files is best to use the socket communication method to ensure the stability of the program.) )

Let's take the first example:

static String strURL = "http://www.baidu.com";

 Public Static voidtesthttpurlconnection () {NewThread (NewRunnable () {PrivateHttpURLConnection Conn;  Public voidrun () {Try{URL URL=NewURL (strURL); Conn=(HttpURLConnection) url.openconnection (); Conn.setrequestmethod ("GET");//Set Request ModeConn.setconnecttimeout (6 * 1000);//set the time when the connection timed outConn.setreadtimeout (8000);//set the number of milliseconds to read timeout                                        if(Conn.getresponsecode ()! = 200)//determine if the request is successful                        Throw NewRuntimeException ("Run Exception"); //gets the input stream returned by the serverInputStream is =Conn.getinputstream (); String Str=convertstreamtostring (IS); System.out.println ("HttpURLConnection Way" +str); } Catch(Exception e) {System.out.println ("Utils Exception");                E.printstacktrace (); }                //Close the HTTP linkConn.disconnect ();    }}). Start (); }

Change the flow to a string

/*** Change the flow to a string * *@paramis *@return     */     Public StaticString convertstreamtostring (InputStream is) {/** To convert the InputStream to String we use the * Bufferedreader.readline () method. We iterate until the BufferedReader * return null which means there ' s no more data to read.         Each line would * appended to a StringBuilder and returned as String. */BufferedReader Reader=NewBufferedReader (NewInputStreamReader (IS)); StringBuilder SB=NewStringBuilder (); String Line=NULL; Try {             while(line = Reader.readline ())! =NULL) {sb.append ( line+ "\ n"); }        } Catch(IOException e) {e.printstacktrace (); } finally {            Try{is.close (); } Catch(IOException e) {e.printstacktrace (); }        }        returnsb.tostring (); }

Run the program and the test results are as follows:

Get Web page success.

Next, let's simply recognize HttpClient:

HttpClient is a sub-project under Apache Jakarta common to provide an efficient, up-to-date, feature-rich client programming toolkit that supports the HTTP protocol, and it supports the latest versions and recommendations of the HTTP protocol. HttpClient has been used in many projects, such as the two other open source projects that are famous on Apache Jakarta Cactus and Htmlunit use httpclient.

HttpClient has increased ease of use and flexibility compared to the urlconnection of traditional JDK. It is not only easy for the client to send HTTP requests, but also facilitates the developer to test the interface (based on the HTTP protocol), which improves the efficiency of the development and facilitates the robustness of the code.

We use HttpClient to achieve the above httpurlconnection get Baidu Web page the same function.

 Public Static voidtesthtppclient () {NewThread (NewRunnable () {@Override Public voidrun () {HttpClient client=Newdefaulthttpclient (); HttpGet Request=NewHttpGet (strURL);                HttpResponse response; Try{Response=Client.execute (Request); if(Response.getstatusline (). Getstatuscode () = =HTTPSTATUS.SC_OK) {String str=entityutils.tostring (Response.getentity ()); System.out.println ("Htppclient Implementation Mode" +str); }                } Catch(clientprotocolexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace ();    }}). Start (); }

The results are as follows:

At the moment, the most common and simplest use of two HTTP communications is all we have. As for the two communication methods of further use, we need to learn and understand further, refueling!

Android HTTP Network programming (i)

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.