http://blog.csdn.net/wolf09311/article/details/41012379
1) Java.net of the Android platform network-related API interface a).*(Standard Java interface) java.net.* Provides networking-related classes, including streams, packet sockets, Internet protocols, common HTTP processing, and more. For example: Create URLs, and urlconnection/httpurlconnection objects, set link parameters, link to the server, write data to the server, read data from the server, and so on. These are all involved in Java network programming. b) The Org.apache interface is not enough for most applications to provide the network functionality of the JDK itself, which requires the Apache HttpClient provided by Android. It is an open source project that is more functional and provides efficient, up-to-date, feature-rich toolkit support for client HTTP programming. c) android.net.*(Android network interface) often use the class under this package for Android-specific network programming, such as: Access to WiFi, access to Android Internet Information, mail and other functions. 2There are two main modes of network architecture b/s,c/S B/S----"is the browser/server-side mode, through the application layer of the HTTP protocol communication, do not need specific client software, but need a uniform specification of the client, in short, the Android Web browser (such as Chrome,ucweb,qq browser, etc.) access to the Web server side way. C/S-----"on the client/server-side mode, which communicates through any network protocol, requires specific client software. 3The server side returns the contents of the client in three ways: a) returned as HTML code. b) returns as an XML string, which is much more in the way Android is developed. The returned data needs to be parsed by XML parsing (SAX, dom,pull, etc) (prerequisite knowledge). c) returned as a JSON object. Android's network programming is divided into 2 types: HTTP protocol-based, and socket-based, HTTP protocol based TCP/protocols on IP protocols1. 1HttpURLConnection Connection URL1) to create a URL object URL url=NewURL (http://www.baidu.com);2use HttpURLConnection objects to get web page data from the network HttpURLConnection conn=(HttpURLConnection) url.openconnection ();3) To set the connection timeout conn.setconnecttimeout (6* +);4) to determine the response codeif(Conn.getresponsecode ()! = $)//get a webpage from the Internet, send a request, read the page back in a streamThrow NewRuntimeException ("Request URL failed");5) gets the input stream returned by the network InputStream is=Conn.getinputstream ();6) String result = ReadData ( is,"GBK");//file stream input out file with Outstream.write7) Conn.disconnect (); Summary:--Remember to set the connection timeout and if the network is not good, the Android system will retract the resource interruption operation over the default time.--returns the response code 200, which is successful.--The operation of the file stream in Android is the same as in Java SE.--in the operation of the large file, write the file to SDcard, do not write directly to the phone memory.--operation of large files is to read from the network over and over again to write to SDcard, reduce the use of cell phone memory. This is important, and interviews are often asked.--When you are done with the file stream, remember to close it promptly.1. 2 to send the request parameter to the server side step:1) to create the URL object: URL Realurl =NewURL (requesturl);2) sends a request to the network address via the HttpURLConnection object HttpURLConnection Conn=(HttpURLConnection) realurl.openconnection ();3) Set the allowable output: Conn.setdooutput (true);4) setting does not use the cache: Conn.setusecaches (false);5) set to send using post: Conn.setrequestmethod ("POST");6) set to maintain long connection: Conn.setrequestproperty ("Connection","keep-alive");7) Set file Character set: Conn.setrequestproperty ("Charset","UTF-8");8) Set file length: Conn.setrequestproperty ("Content-length", String.valueof (data.length));9) Set File type: Conn.setrequestproperty ("Content-type","application/x-www-form-urlencoded");Ten) to set the HTTP request Header Conn.setrequestproperty ("Accept "," Image/gif, Image/jpeg, Image/pjpeg, Image/pjpeg, application/x-Shockwave-flash, Application/xaml+xml, Application/vnd.ms-xpsdocument, APPLICATION/X-MS-XBAP, Application/x-ms-application, Application/vnd.ms-excel, Application/vnd.ms-powerpoint, Application/msword, */*"); setting language: Conn.setrequestproperty ("accept-language ","Zh-cn");Conn.setrequestproperty ("Conn.setrequestproperty (" One) is output as a stream. Summary:--send POST request must set allow output--do not use caching, prone to problems.--the start of the Setrequestproperty () setting with the HttpURLConnection object is to generate the HTML file header.1.3Sending XML data (also known as entity entities) to the server is the standard language for communication, and the Android system can also transmit data by sending an XML file.1Writes the generated XML file to a byte array and is set to utf-8:byte[] Xmlbyte = Xml.tostring (). GetBytes ("UTF-8");2) to create the URL object and specify the address and parameters: url url =NewURL (http://localhost:8080/itcast/contanctmanage.do?method=readxml);3) Get link: httpurlconnection conn =(HttpURLConnection) url.openconnection ();4) Set Connection timeout: Conn.setconnecttimeout (6* +);5) set allow output Conn.setdooutput (true);6) setting does not use the cache: Conn.setusecaches (false);7) settings are transferred as Post: Conn.setrequestmethod ("POST"); 8) Maintain long connection: Conn.setrequestproperty ("Connection","keep-alive");9) sets the character set: Conn.setrequestproperty ("Charset","UTF-8");Ten) sets the total length of the file: Conn.setrequestproperty ("Content-length", String.valueof (xmlbyte.length)); One) Set File type: Conn.setrequestproperty ("Content-type","text/xml; Charset=utf-8"); A) sends the XML data as a file stream: Outstream.write (xmlbyte); Summary:--we use HTML to transfer files, which can only transfer files that are normally 5M in the same way.--transferring large files is not suitable for HTML, transferring large files We are going to do socket programming. Ensure program stability--Save the address and parameters in a byte array:byte[] data =params. ToString (). GetBytes ();1.4using Apache's httpclient to implement Android client sending entity entities above for direct use of HTTP protocol, in fact, Android has integrated third-party open source projects-------Org.apache.http.client.HttpClient, you can refer directly to the API it provides. HTTP clients encapsulate a smorgasbord of objects required to execute HTTP requests whilehandling cookies, authentication, connection management, and other features. Thread Safety of HTTP clients depends on the implementation and configuration of the specific client. When using the Post method for parameter passing, you need to use N Amevaluepair to save the parameters to be passed. In addition, you need to set the character set you are using. Socket programming based on socket communication provides higher transmission efficiency, more powerful functions and more flexible control than URL-based network programming. In Java is already the lowest level of the network programming interface, in Java to directly manipulate the lower level of the protocol, it is only the use of JNI, which is basically a local language category. Third, other network-related technologies3.1, Android WebView controls are embedded in the form of Web pages in the Android app. In addition, HTML can be implemented via WebView<------->javascript<-------->Android Java Interaction, access to local phone hardware. For example:1) webview.addjavascriptinterface (Object obj, String InterfaceName) method, which allows the Java method to be called in JavaScript;voidaddjavascriptinterface (Object obj, String InterfaceName) use Thisfunction to bind anObjectTo JavaScript so, the methods can be accessed fromJavaScript.2) in Java, call the method in JavaScript script Webview.loadurl ("javascript:show ('"+json+"')");//Call JS's Show method3.2 interaction------------based on SOAP protocol and WebService NetworkKSoap2 Simple Object Access protocol, Simple Object Access Protocol (SOAP) is a lightweight, simple, XML-based protocol. Ksoap2 via a third-party rack package-android-assembly-2.4-jar-with-Dependencies.jar, we can make requests to the server to invoke the services we need. 3.3implement server push through the establishment of a persistent connection method, the server sends information to the mobile phone Android users. Method One: Mqtt protocol (instance Android+php)1, the server side needs to download the installation of IBM's really Small Message broker (RSMB) (MQTT protocol proxy) and run Broker;:http://WWW.ALPHAWORKS.IBM.COM/TECH/RSMB2, PHP server-side PHP libraries written for mqtt (download link for Tokudu phpmqtt Communication Project), where send_mqtt.php is a PHP script that receives messages via post and sends messages to RSMB via the SAM;3, Instance Download: Description: http://Tokudu.com/2010/how-to-implement-push-notifications-for-android/Android Client: https://Github.com/tokudu/androidpushnotificationsdemoPHP Server side: https://github.com/tokudu/phpmqttclientmethod Two: XMPP protocol (instance Android+JSP) xmpp:the extensible Messaging and Presence Protocol (extensible Communication and Presentation Protocol) XMPP is based on the Jabber protocol, and Jabber is an open protocol commonly used in instant messaging. : http://sourceforge.net/projects/androidpn/files/unzip the server side, click Bin/run.bat Run, Access: http://127.0.0.1:7070/index.do, you can look at the server-side management page, with this management page, you need to push messages to the client. method Three: Use APNs (Android Push Notification Service) http://www.push-notification.org/APNS (Android Push Notification Service) is a solution that easily implements Push Notification on Android. Simply request an API Key and follow the easy steps to implement PU function of SH notification. S
View Code
Android Network Programming Knowledge Framework