Android Network Programming Overview
First of all, there are a few questions to be aware of:
1) Android Platform network-related API interface
A) java.net.* (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 other communications. These are all involved in Java network programming.
b) Org.apache interface
For most applications, the JDK itself provides a far less network capability than the Android-provided Apache HttpClient. 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.
2) There 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 to standardize the client, in short, is the Android Web browser (such as Chrome,ucweb, QQ Browser, etc.) to access the Web server side of the way.
C/S-----"in the client/server-side mode, through any network protocol communication, the need for specific client software."
3) The server side returns the contents of the client in three ways:
A) is 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
First, the HTTP protocol
protocol based on TCP/IP protocol
1.1HttpURLConnection Connection URL
1) Create a URL object
URL url = new URL (http://www.baidu.com);
2) Get web page data from the network using HttpURLConnection objects
HttpURLConnection conn = (httpurlconnection) url.openconnection ();
3) Set the connection timeout
Conn.setconnecttimeout (6*1000);
4) to determine the response code
if (Conn.getresponsecode ()! = 200)//Get the Web page from the Internet, send a request, and read the page back in the form of a stream
throw new RuntimeException ("Request URL failed");
5) Get the input stream returned by the network
InputStream is = Conn.getinputstream ();
6) String result = ReadData (IS, "GBK"); File stream input out file with Outstream.write
7) Conn.disconnect ();
Summarize:
--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.
--When working with large files, write the files to SDcard and do not write directly to the phone memory.
--operation of large files is to read from the network 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 flow, remember to close it promptly.
1.2 Sending request parameters to server side
Steps:
1) Create URL object: url realurl = new URL (requesturl);
2) Send the request to the network address via the HttpURLConnection object
HttpURLConnection conn = (httpurlconnection) realurl.openconnection ();
3) Set allowable output: Conn.setdooutput (True);
4) Set not to use 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");
10) Set the HTTP request header
C Onn.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 ("
11) output in stream mode.
Summarize:
--Send POST request must set allow output
--Do not use the cache, prone to problems.
--At the beginning of the Setrequestproperty () setting of the HttpURLConnection object, the HTML file header is generated.
1.3. Sending XML data (also known as entity entities) to the server side
The XML format is the standard language for communication, and the Android system can also transmit data by sending an XML file.
1) write the resulting XML file into a byte array and set it to utf-8:byte[] Xmlbyte = xml.tostring (). GetBytes ("UTF-8");
2) Create the URL object and specify the address and parameters: url url = new URL (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) Set not to use cache: Conn.setusecaches (false);
7) settings are transmitted by post: Conn.setrequestmethod ("post");
8) Maintain long connection: Conn.setrequestproperty ("Connection", "keep-alive");
9) Set CharSet: Conn.setrequestproperty ("Charset", "UTF-8");
10) Total length of the Set file: Conn.setrequestproperty ("Content-length", String.valueof (Xmlbyte.length));
11) Set File type: Conn.setrequestproperty ("Content-type","Text/xml; Charset=utf-8 ");
12) Send XML data as a file stream: Outstream.write (xmlbyte);
Summary:
-we use HTML to transfer files, which can only transfer files that are typically 5M in a way.
-Transfer large files in a way that is not suitable for HTML transmission of large files We are going to program for sockets. Ensure the stability of your programs
--Store the address and parameters in a byte array: byte[] data = params.tostring (). GetBytes ();
1.4 using Apache's httpclient to enable Android clients to send entity entities
The above is the direct use of the HTTP protocol to achieve, in fact, Android has integrated the third party Open source project-------Org.apache.http.client.HttpClient, can directly refer to the API it provides use.
HTTP clients encapsulate a smorgasbord of objects required to execute HTTP requests while handling cookies, authentication , connection management, and other features. Thread Safety of HTTP clients depends on the implementation and configuration of the specific client.
When you use the Post method for parameter passing, you need to use Namevaluepair to hold the arguments you want to pass. In addition, you need to set the character set you are using.
Second, socket-based communication
socket Programming provides higher transmission efficiency, more powerful functionality, 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 technologies
3.1. Android WebView Control
embed the form of a webpage in the Android app.
In addition, WebView enables html<------->javascript<-------->android Java interaction to access local phone hardware.
For example:
1) webview.addjavascriptinterface (Object obj, String InterfaceName)method, which allows the Java method to be called in JavaScript;
| void |
Addjavascriptinterface (Object obj, String InterfaceName) The use of this function to bind a object to JavaScript so, the methods can is accessed from JavaScript. |
2) Methods in Java to invoke JavaScript scripts
Webview.loadurl ("Javascript:show ('" +json+ ")");//Invoke JS's Show method
3.2 Interaction------------based on SOAP protocol and WebService network KSoap2
the Simple Object Access Protocol , Simple Object Access Protocol (SOAP) is a lightweight, simple, XML-based protocol.
Through the Ksoap2-android-assembly-2.4-jar-with-dependencies.jar provided by the third party, we can request the service to the server to call our own.
3.3 Implementing Server Push
By establishing a persistent connection method, the server sends information to the mobile Android user.
Method One: Mqtt protocol (instance android+php)
1, the server needs to download and install IBM really Small Message broker (RSMB) (MQTT Protocol agent), and run the broker;
: HTTP://WWW.ALPHAWORKS.IBM.COM/TECH/RSMB
2. PHP server-side PHP library written by Sam for Mqtt (download link is 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. Example Download:
Description: Http://tokudu.com/2010/how-to-implement-push-notifications-for-android/
Android Client: Https://github.com/tokudu/AndroidPushNotificationsDemo
PHP Server side: https://github.com/tokudu/PhpMQTTClient
Method 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 of the 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 for easy Push Notification on Android. Simply request an API Key to implement the push notification functionality in a simple step.
3.4 PhoneGap
Referring to the mobile 3G era of network applications, have to mention the PhoneGap.
PhoneGap uses Html,css,javascript to support Android, Iphone,windows Phone, Palm OS, Sybian ....
If you consider developing an application for most smartphones, PhoneGap is one of the development frameworks that you can consider.
RELATED links:
1. Encapsulates an auxiliary class for an HTTP request,http://blog.csdn.net/ihrthk/article/details/7739834