Full analysis of Android Web application development

Source: Internet
Author: User
Tags set time

?? Android Web application development, mainly in two ways, one is the socket (is the TCP/UDP Protocol encapsulation), the other is the use of the HTTP protocol, Android mainly provides two ways, HttpURLConnection and Apache HttpClient. The following is a specific description of Android Web application development.

One, socket-based network communication 1, UDP-based socket programming steps
    1. Define Dock
      That is: Define a Datagramsocket object ds

    2. Define containers that can be used to receive or send data
      That is: Define the Datagrampacket object DP

    3. receiving data from a container on the dock (Ds.receive (DP))

    4. Close the pier (Ds.close ())

2, TCP-based socket programming steps

Ii. using the HTTP protocol to access network resources 1, HttpURLConnection

?? The basic functionality of accessing the HTTP protocol is already provided in the JDK's java.net package: HttpURLConnection. HttpURLConnection is the standard class for Java, and HttpURLConnection inherits from URLConnection, which can be used to send a GET request, POST request to a specified Web site.

Here is a tool class that accesses the network using a GET request for the HttpURLConnection class:

The /** * getInputStream function is to get a byte input stream that reads server-side resources * @param path is a URL string * @return InputStream */     Public StaticInputStreamgetInputStream(String Path) {URL url =NULL;Try{URL =NewURL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection ();//Set Request modeConn.setrequestmethod ("GET");//Set time-out for connectionConn.setconnecttimeout ( the);//settings can read data from server sideConn.setdoinput (true);//Get the server-side response code            if(Conn.getresponsecode () = = $) {//Get a byte input stream that reads server-side ResourcesInputStream in = Conn.getinputstream ();returnIn }        }Catch(Malformedurlexception e) {//TODO auto-generated catch blockE.printstacktrace (); }Catch(IOException e) {//TODO auto-generated catch blockE.printstacktrace (); }return NULL; }
2. Apache HttpClient

?? The HTTP protocol is probably the most widely used and most important protocol on the Internet now, and more and more Java applications need to access network resources directly through the HTTP protocol. While the basic functionality of accessing the HTTP protocol has been provided in the Java NET package of the JDK, the JDK library itself provides a lack of functionality and flexibility for most applications. 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 is an enhanced version of Httpurlconnection,httpurlconnection can do things httpclient all can do; httpurlconnection does not provide some features, HttpClient is also provided, but it is focused on how to send requests, receive responses, and manage HTTP connections.

Here is the tool class for accessing the network using the HttpClient get method:

    /** * Read input stream, return data * @param stream * @return * *     Public Static byte[]Readstream(InputStream Stream)throwsioexception{byte[] ret =NULL; Bytearrayoutputstream bout =NewBytearrayoutputstream ();byte[] buf =New byte[ -];intLen while(true) {len = Stream.read (BUF);if(len = =-1) { Break; } bout.write (BUF,0, Len); }//Force release of temporary resourcesBUF =NULL;        ret = Bout.tobytearray (); Bout.close ();returnRet }/** * Get Request method * @param URL address * @return  */     Public Static byte[]Doget(String URL) {byte[] ret =NULL; HttpGet request =NewHttpGet (URL); HttpClient client =NewDefaulthttpclient ();Try{HttpResponse response = Client.execute (request); Statusline statusline = Response.getstatusline ();intStatusCode = Statusline.getstatuscode ();if(StatusCode = = $) {httpentity entity = response.getentity (); InputStream stream = Entity.getcontent ();//Returns the actual dataret = Readstream (stream);            Stream.Close (); }        }Catch(IOException e)        {E.printstacktrace (); }returnRet }
3. The difference between httpurlconnection and httpclient

?? Prior to the Android 2.2 version, HttpClient had fewer bugs, so using it was the best option. HttpURLConnection is the best choice for Android version 2.3 and beyond. For new applications, you should be more inclined to use httpurlconnection.

Specific reference: Android access to the network, using HttpURLConnection or httpclient? http://blog.csdn.net/guolin_blog/article/details/12452307

Full analysis of Android Web application development

Related Article

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.