Android Three network communication methods and the network communication mechanism of Android _android

Source: Internet
Author: User
Tags readline stringbuffer

The Android platform has three network interfaces that can be used: 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 (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 involved in Java network programming, we look at a simple socket programming, to implement the server postback client information.

Here is an example to illustrate:

A, client:

New Android Project Project: Socketforandroid (This is a random 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:o" rientation= "vertical" >
 <textview
  android:layout_width= "Fill_parent"
  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 savedinstancestate) {super.oncreate (savedinstancestate);
  Setcontentview (R.layout.activity_main);
  Initializes two UI Control 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) {S
    Ocket socket = NULL;
    Gets the input in the message input String msg = Message.gettext (). toString () + "\ r \ n"; Try {//here must be 192.168.3.200, can not be localhost or 127.0.0.1 socket = new Socket ("192.168.3.200", 18888); PrintWriter out = new PrintWriter (new BufferedWriter (New OutputStreamWriter (socket.getoutput
     Stream ()), true);
     Send Message Out.println (msg);
     Receive data BufferedReader in = new BufferedReader (New InputStreamReader (Socket.getinputstream ())
     );
     Read 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 wrong!");
     //Close various streams out.close ();
    In.close ();
    catch (IOException e) {e.printstacktrace ();
      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 network permissions:

<uses-permission android:name= "Android.permission.INTERNET"/>

B, 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);
 Loops Listen for client link requests while (true) {System.out.println ("start ...");
 Receive Request Socket = server.accept ();
 System.out.println ("Accept ...");
 Receive client message 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 (New OutputStreamWriter (Socket.getoutputstream)), tr
 UE);
 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 out "start ..." String!

D, run the Android project file, as shown below:

Enter the following string in the input box, click the Send button:

The server receives the message from the client and prints it to the console:

2. Apache Interface

For most applications, the JDK itself offers far less network functionality, and this requires the Apache HttpClient provided by Android. It is an open source project that is more functional and provides efficient, up-to-date, and feature-rich toolkit support for client-side HTTP programming.
Let's take a simple example to see how to use HttpClient to access the Web on the Android client.
First of all, to build a Web application 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, code 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;
 Private 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 emulator has
   It itself as a 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 a request by post, access to the web * * @param URL web address * @return Response data */private string post (string url) {Buffer
  Edreader reader = null;
  StringBuffer SB = null;
  String result = ""; HttpClient client = new DefaulthttPclient ();
  HttpPost requset = new HttpPost (URL);
  Save the parameters to be passed 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 (response.getentity (). GetContent ()) (new InputStreamReader);
    SB = new StringBuffer ();
    String line = "";
    String NL = System.getproperty ("Line.separator");
    while (line = Reader.readline ())!= null) {sb.append (line);
  A 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 way, access Web * * * @param URL web address * @return Response data */private static String get (string url) {Buff
  Eredreader BufferedReader = null;
  StringBuffer SB = null;
  String result = "";
  HttpClient client = new Defaulthttpclient ();
  HttpGet request = new HttpGet (URL);
   Send a request, get a response try {httpresponse response = Client.execute (request); The request succeeded if (Response.getstatusline (). Getstatuscode () = = BufferedReader = new BufferedReader (New inputs
    Treamreader (Response.getentity (). GetContent ()));
    SB = new StringBuffer ();
    String line = "";
    String NL = System.getproperty ("Line.separator");
    while (line = Bufferedreader.readline ())!= null) {sb.append (line); The 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:o" rientation= "vertical" >
 <textview
  android:id= "@+id/textview" android:layout_width= "Fill_"
  Parent "
  android:layout_height=" wrap_content "
  android:gravity=" center "
  android:text=" Select different ways to access the page through the button "/>
 <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:

The classes under this package are often used for Android-specific network programming, such as access to WiFi, access to Android networking information, mail, and more.
Here is not a detailed example, because this contact more ~ ~ ~.

Here to introduce Android network communication

We know that Java provides the socket to complete the communication between the two PC computers. TCPServer needs the client and server, the server uses Socketserver and the socket completes, the client uses the socket to complete ... We are all familiar with these. This chapter is mainly through TCPServer to complete the Android and PC communication,

First we look at the familiar server program:

The diagram above uses the main method main other thread, and then in the Run method to listen to the content of the sent, if the content is output. Using the Java API, very 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.

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.