Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 資訊

Android 三大網絡通信方式詳解

編輯:Android 資訊

Android 平台有三種網絡接口可以使用,分別是:java.net.*(標準 Java 接口)、Org.apache 接口和 Android.net.*(Android 網絡接口)。下面分別介紹這些接口的功能與作用。

1. 標準 Java 接口

java.net.* 提供了與聯網相關的類,包括流、數據包套接字(socket)、Internet 協議、常見 Http 處理等。比如創建 URL 以及 URLConnection/HttpURLConnection 對象、設置鏈接參數、鏈接到服務器、向服務器寫數據、從服務器讀取數據等通信操作。這些在 Java 網絡編程中均有涉及。我們看一個簡單的 socket 編程示例,實現服務器回發客戶端信息。

A、客戶端:

新建 Android 項目工程:SocketForAndroid(名字隨意起,筆者以這個為例)。下面是 main_activity.xml 的代碼:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://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 的代碼如下:

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);
        // 初始化兩個 UI 控件
        message = (EditText) findViewById(R.id.message);
        send = (Button) findViewById(R.id.send);
        // 設置發送按鈕的點擊事件響應
        send.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                Socket socket = null;
                // 獲取 message 輸入框裡輸入的內容
                String msg = message.getText().toString() + "/r/n";
                try {
                    // 這裡必須是 192.168.3.200,不可以是 localhost 或 127.0.0.1
                    socket = new Socket("192.168.3.200", 18888);
                    PrintWriter out = new PrintWriter(
                        new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
                    // 發送消息
                    out.println(msg);
                    // 接收數據
                    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    // 讀取接收的數據
                    String msg_in = in.readLine();
                    if (null != msg_in) {
                        message.setText(msg_in);
                        System.out.println(msg_in);
                    } else {
                        message.setText("接收的數據有誤!");
                    }
                    // 關閉各種流
                    out.close();
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (null != socket) {
                            // socket 不為空時,最後記得把它關閉
                            socket.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}

最後別忘了添加訪問網絡的權限:

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

B、服務端:

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);
            // 循環監聽客戶端鏈接請求
            while (true) {
                System.out.println("start...");
                // 接收請求
                socket = server.accept();
                System.out.println("accept...");
                // 接收客戶端消息
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String message = in.readLine();
                System.out.println(message);
                // 發送消息,向客戶端
                PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
                out.println("Server:" + message);
                // 關閉流
                in.close();
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != socket) {
                try { socket.close(); } catch (IOException e) { e.printStackTrace(); }
            }
        }
    }
    // 啟動服務器
    public static void main(String[] args) {
        Thread server = new Thread(new ServerAndroid());
        server.start();
    }
}

C、啟動服務器,控制台會打印出「start…」字符串。

D、運行 Android 項目,如下圖:

在輸入框裡輸入字符串,點發送按鈕:

服務器收到客戶端發來的消息並打印到控制台:

2. Apache 接口

對於大部分應用來說,JDK 本身提供的網絡功能遠遠不夠,這時就需要 Android 提供的 Apache HttpClient 了。它是一個開源項目,功能更完善,為客戶端 Http 編程提供了高效、最新、功能豐富的工具包支援。下面用一個簡單例子看看如何在 Android 客戶端用 HttpClient 訪問 Web。

首先在機器上搭建一個名為 test 的 web 應用,包含兩個簡單的 PHP 文件:hello_get.php 和 hello_post.php,內容如下:

hello_get.php:

<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
You connected this page on : <?php echo $_GET["get"]; ?>
</body>
</html>

hello_post.php:

<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
You connected this page on : <?php echo $_POST["post"]; ?>
</body>
</html>

在原 Android 項目裡新建一個 Apache 活動類 Apache.java,代碼如下:

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;
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) {
            // 注意:此處 ip 不能用 127.0.0.1 或 localhost,Android 模擬器已把它自己作為了 localhost
            String url = "https://192.168.3.200/test/hello_get.php?name=yaowen&get=GET";
            textView.setText(get(url));
        }
        if (v.getId() == R.id.post) {
            String url = "https://192.168.3.200/test/hello_post.php";
            textView.setText(post(url));
        }
    }
    /** 以 post 方式發送請求,訪問 web */
    private String post(String url) {
        BufferedReader reader = null;
        StringBuffer sb = null;
        String result = "";
        HttpClient client = new DefaultHttpClient();
        HttpPost requset = new HttpPost(url);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        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() == 200) {
                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 (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != reader) {
                try { reader.close(); } catch (IOException e) { e.printStackTrace(); }
            }
            if (null != sb) { result = sb.toString(); }
        }
        return result;
    }
    /** 以 get 方式發送請求,訪問 web */
    private static String get(String url) {
        BufferedReader bufferedReader = null;
        StringBuffer sb = null;
        String result = "";
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        try {
            HttpResponse response = client.execute(request);
            if (response.getStatusLine().getStatusCode() == 200) {
                bufferedReader = new BufferedReader(new InputStreamReader(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(); } catch (IOException e) { e.printStackTrace(); }
            }
            if (null != sb) { result = sb.toString(); }
        }
        return result;
    }
}

新建一個 apache.xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://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="通過按鈕選擇不同方式訪問網頁" />
    <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>

運行結果如下:

3. android.net 編程

我們常使用此包下的類進行 Android 特有的網絡編程,如訪問 WiFi、獲取 Android 聯網信息、郵件等功能。這裡就不詳細舉例了,因為這塊接觸得比較多~~~

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved