The Android platform is available in three network interfaces: java.net.* (Standard Java interface), Org.apache interface, and android.net.* (Android network interface). The functions and roles of these interfaces are described below.
1. 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 involved in Java network programming, we look at a simple socket programming, to implement server postback client information.
Here is an example to illustrate:
A, client:
New Android Project: Socketforandroid (This is a casual name, I was built with this!) )
Here is the code for Main_activity.xml:
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Fill_parent "android:layout_height=" fill_parent "android:orientation=" vertical " > <textview android:layout_width= "fill_parent" android:layout_height= "Wrap_content" android: text= "@string/hello"/> <edittext android:id= "@+id/message" android:layout_width= "Match_parent" android:layout_height= "wrap_content" android:hint= "@string/hint"/> <button android:id= "@+id/ Send " android:layout_width=" fill_parent " android:layout_height=" wrap_content " android:text=" @ String/send "/></linearlayout>
Mainactivity.java code into the following:
Package Com.yaowen.socketforandroid;import Android.os.bundle;import android.support.v7.app.AppCompatActivity; Import Android.view.view;import android.widget.button;import Android.widget.edittext;import Java.io.BufferedReader ; Import Java.io.bufferedwriter;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.io.outputstreamwriter;import Java.io.printwriter;import Java.net.socket;public class MainActivity extends appcompatactivity {private EditText message; private Button send; @Override protected void onCreate (Bundle savedinstances Tate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Initializes two UI controls, message = (EditText) Findviewbyid (r.id.message); Send = (Button) Findviewbyid (r.id.send); Set the Click event Response for the Send button Send.setonclicklistener (new View.onclicklistener () {@Override public void OnClick (View v) {Socke t socket = null; Gets the input contents of the Message input box, String msg = Message.gettext (). toString () + "\ r \ n"; try {//Must be 192.168.3.200 here, notcan be localhost or 127.0.0.1 socket = new Socket ("192.168.3.200", 18888); PrintWriter out = new PrintWriter (new BufferedWriter (New OutputStreamWriter (socket.getoutputstr EAM ())), true); Send Message Out.println (msg); Receive data BufferedReader in = new BufferedReader (New InputStreamReader (Socket.getinputstream ())); Reads the received data String msg_in = In.readline (); if (null! = msg_in) {message.settext (msg_in); System.out.println (msg_in); } else {Message.settext ("The data received is incorrect!"); }//Close various flow out.close (); In.close (); } catch (IOException e) {e.printstacktrace (); When the finally {try {if (null! = socket) {//socket is not empty, remember to close the socket Socket.close (); }} catch (IOException e) {e.printstacktrace (); } } } }); }}
Finally, don't forget to add access to network permissions:
<uses-permission android:name= "Android.permission.INTERNET"/>
B, the service side:
Package Service;import Java.io.bufferedreader;import Java.io.bufferedwriter;import java.io.ioexception;import Java.io.inputstreamreader;import Java.io.outputstreamwriter;import Java.io.printwriter;import Java.net.serversocket;import Java.net.socket;public class Serverandroid implements Runnable {@Override public void run ( {SOCKET socket = null; try {serversocket server = new ServerSocket (18888);//Loop Listener Client link request while (true) {SYSTEM.OUT.PR Intln ("Start ..."); Receive Request Socket = server.accept (); System.out.println ("Accept ..."); Receive client messages BufferedReader in = new BufferedReader (New InputStreamReader (Socket.getinputstream ())); String message = In.readline (); SYSTEM.OUT.PRINTLN (message); Send a message to the client printwriter out = new PrintWriter (New BufferedWriter (Socket.getoutputstream ())), true); Out.println ("Server:" + message); Close flow in.close (); Out.close (); }} catch (IOException e) {e.printstacktrace ();} finally {if (null! = socket) {try {socket.close ()} catch (IOException e) {e.printstacktrace ();}} }}//start server public static void main (string[] args) {Thread server = new Thread (new Serverandroid ()); Server.start ();}}
C, start the server, the console will print a "start ..." String!
D. Run Android project files, such as:
Enter the following string in the input box and click the Send button:
The server receives a message from the client and prints it to the console:
2. 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.
Let's look at a simple example of how to use HttpClient to access the Web on an Android client.
First, to build a web App test on your machine, there are two very simple PHP files: hello_get.php and hello_post.php!
The contents are as follows:
The code for hello_get.php is as follows:
The code for hello_post.php is as follows:
Create a new Apache activity class in the original Android project: Apache.java, the code is as follows:
Package Com.yaowen.socketforandroid;import Android.os.bundle;import android.support.v7.app.AppCompatActivity; Import Android.view.view;import Android.widget.button;import Android.widget.textview;import Org.apache.http.httpentity;import Org.apache.http.httpresponse;import Org.apache.http.namevaluepair;import Org.apache.http.client.clientprotocolexception;import Org.apache.http.client.httpclient;import Org.apache.http.client.entity.urlencodedformentity;import Org.apache.http.client.methods.httpget;import Org.apache.http.client.methods.httppost;import Org.apache.http.impl.client.defaulthttpclient;import Org.apache.http.message.basicnamevaluepair;import Java.io.bufferedreader;import Java.io.IOException;import Java.io.inputstreamreader;import Java.io.unsupportedencodingexception;import Java.util.ArrayList;import java.util.list;/** * Created by Yaowen on 2015/11/10. */public class Apacheactivity extends Appcompatactivity implements View.onclicklistener {private TextView TextView; priv Ate butTon Get1, Post1; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.apache); TextView = (TextView) Findviewbyid (R.id.textview); Get1 = (Button) Findviewbyid (r.id.get); Post1 = (Button) Findviewbyid (r.id.post); Get1.setonclicklistener (this); Post1.setonclicklistener (this); } @Override public void OnClick (View v) {if (V.getid () = = R.id.get) {//NOTE: IP cannot be used here 127.0.0.1 or localhost,android simulator has made it itself For the localhost String url = "Http://192.168.3.200/test/hello_get.php?name=yaowen&get=GET"; Textview.settext (Get (URL)); } if (V.getid () = = R.id.post) {String url= "http://192.168.3.200/test/hello_post.php"; Textview.settext (post (URL)); }}/** * Send request by post, Access Web * * @param URL web address * @return Response data */Private String post (string url) {BufferedReader reader = null; StringBuffer SB = null; String result = ""; HttpClient client = new Defaulthttpclient (); HttpPost requset = new HttpPost (URL); Save the parameters to pass list<namevaluepair> params = new arraylist<namevaluepair> (); Add parameter Params.add (new Basicnamevaluepair ("name", "Yaowen")); Params.add (New Basicnamevaluepair ("POST", "post")); try {httpentity entity = new Urlencodedformentity (params, "utf-8"); Requset.setentity (entity); HttpResponse response = Client.execute (Requset); if (Response.getstatusline (). Getstatuscode () = = () {System.out.println ("post success"); reader = new BufferedReader (New InputStreamReader (Response.getentity (). GetContent ())); SB = new StringBuffer (); String line = ""; String NL = System.getproperty ("Line.separator"); while (line = Reader.readline ())! = null) {sb.append (line); }}} catch (Unsupportedencodingexception e) {e.printstacktrace (); } catch (Clientprotocolexception e) {e.printstacktrace (); } catch (IOException e) {e.printstacktrace (); } finally {if (null! = Reader) {try {reader.close (); } catch (IOException e) {e.printstacktrAce (); }} if (null! = SB) {result = Sb.tostring (); }} return result; }
/** * Send request in Get mode, Access Web * * @param URL web address * @return Response data */private static string get (string url) {Bufferedreade R bufferedreader = null; StringBuffer SB = null; String result = ""; HttpClient client = new Defaulthttpclient (); HttpGet request = new HttpGet (URL); Send request, get response try {httpresponse response = Client.execute (request); The request succeeds if (Response.getstatusline (). Getstatuscode () = = () {BufferedReader = new BufferedReader (New Inputstre Amreader (Response.getentity (). GetContent ())); SB = new StringBuffer (); String line = ""; String NL = System.getproperty ("Line.separator"); while (line = Bufferedreader.readline ())! = null) {sb.append (line); }}} catch (IOException e) {e.printstacktrace (); } finally {if (null! = BufferedReader) {try {bufferedreader.close (); Bufferedreader=null; } catch (IOException e) {e.printstacktrace (); }} if (null! = SB) {result = Sb.tostring (); }} return result; }}
Create a new Apache. XML file, as follows:
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Fill_parent "android:layout_height=" fill_parent "android:orientation=" vertical " > <textview android:id= "@+id/textview" android:layout_width= "fill_parent" android:layout_ height= "Wrap_content" android:gravity= "center" android:text= "choose different ways to access Web pages via buttons"/> <button Android:id= "@+id/get" android:layout_width= "match_parent" android:layout_height= "Wrap_content " android:text= "Get"/> <button android:id= "@+id/post " android:layout_width= "Match_parent" android:layout_height= "Wrap_content" android:text= "POST"/></linearlayout>
The results run as follows:
3.android.net Programming:
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.
This is not a detailed example, because this contact more than ~ ~ ~.
Let us introduce the Internet communication of Android
We know that the socket provided by Java can complete the communication between two PCs. TCPServer needs the client and server, the server is completed with Socketserver and socket, the client uses the socket to complete ... We are all familiar with these. This chapter mainly completes the communication between Android and PC via TCPServer,
First look at our familiar server programs:
Use the Main method main other thread, and then in the Run method infinite listening to send over the content, if there is content output. Using Java's API, it's classic.
The next step is to send the data to the PC on the Android side with the following code:
This completes the communication between Android and PC.
Network--Three kinds of network communication mode and the network communication mechanism of Android