Android的三種網路通訊方式
阿新 • • 發佈:2019-02-15
Android平臺有三種網路介面可以使用,他們分別是:java.net.*(標準Java介面)、Org.apache介面和Android.net.*(Android網路介面)。下面分別介紹這些介面的功能和作用。
1.標準Java介面
java.net.*提供與聯網有關的類,包括流、資料包套接字(socket)、Internet協議、常見Http處理等。比如:建立URL,以及URLConnection/HttpURLConnection物件、設定連結引數、連結到伺服器、向伺服器寫資料、從伺服器讀取資料等通訊。這些在Java網路程式設計中均有涉及,我們看一個簡單的socket程式設計,實現伺服器回發客戶端資訊。
服務端:
客戶端,MainActivity
佈局檔案:
啟動伺服器:
沒有加訪問網路的許可權:<uses-permission android:name="android.permission.INTERNET"></uses-permission>
IP地址要使用:10.0.2.2
模擬器不能配置代理。
2。Apache介面
對於大部分應用程式而言JDK本身提供的網路功能已遠遠不夠,這時就需要Android提供的Apache HttpClient了。它是一個開源專案,功能更加完善,為客戶端的Http程式設計提供高效、最新、功能豐富的工具包支援。
下面我們以一個簡單例子來看看如何使用HttpClient在Android客戶端訪問Web。
首先,要在你的機器上搭建一個web應用myapp,只有很簡單的一個http.jsp
內容如下:
佈局檔案:
strings.xml
常常使用此包下的類進行Android特有的網路程式設計,如:訪問WiFi,訪問Android聯網資訊,郵件等功能。這裡不詳細講。
1.標準Java介面
java.net.*提供與聯網有關的類,包括流、資料包套接字(socket)、Internet協議、常見Http處理等。比如:建立URL,以及URLConnection/HttpURLConnection物件、設定連結引數、連結到伺服器、向伺服器寫資料、從伺服器讀取資料等通訊。這些在Java網路程式設計中均有涉及,我們看一個簡單的socket程式設計,實現伺服器回發客戶端資訊。
服務端:
- publicclass Server implements Runnable{
- @Override
- publicvoid 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();
- //傳送訊息,向客戶端
- 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();
- }
- }
- }
- }
- //啟動伺服器
- publicstaticvoid main(String[] args){
- Thread server = new Thread(new Server());
- server.start();
- }
- }
客戶端,MainActivity
- publicclass MainActivity extends Activity {
- private EditText editText;
- private Button button;
- /** Called when the activity is first created. */
- @Override
- publicvoid onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- editText = (EditText)findViewById(R.id.editText1);
- button = (Button)findViewById(R.id.button1);
- button.setOnClickListener(new OnClickListener() {
- @Override
- publicvoid onClick(View v) {
- Socket socket = null;
- String message = editText.getText().toString()+ "\r\n" ;
- try {
- //建立客戶端socket,注意:不能用localhost或127.0.0.1,Android模擬器把自己作為localhost
- socket = new Socket("<span style="font-weight: bold;">10.0.2.2</span>",18888);
- PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter
- (socket.getOutputStream())),true);
- //傳送資料
- out.println(message);
- //接收資料
- BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- String msg = in.readLine();
- if (null != msg){
- editText.setText(msg);
- System.out.println(msg);
- }
- else{
- editText.setText("data error");
- }
- out.close();
- in.close();
- } catch (UnknownHostException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- finally{
- try {
- if (null != socket){
- socket.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- });
- }
- }
佈局檔案:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical" android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <TextView android:layout_width="fill_parent"
- android:layout_height="wrap_content" android:text="@string/hello" />
- <EditText android:layout_width="match_parent" android:id="@+id/editText1"
- android:layout_height="wrap_content"
- android:hint="input the message and click the send button"
- ></EditText>
- <Button android:text="send" android:id="@+id/button1"
- android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
- </LinearLayout>
啟動伺服器:
- javac com/test/socket/Server.java
- java com.test.socket.Server
結果如圖:
注意:伺服器與客戶端無法連結的可能原因有:沒有加訪問網路的許可權:<uses-permission android:name="android.permission.INTERNET"></uses-permission>
IP地址要使用:10.0.2.2
模擬器不能配置代理。
2。Apache介面
對於大部分應用程式而言JDK本身提供的網路功能已遠遠不夠,這時就需要Android提供的Apache HttpClient了。它是一個開源專案,功能更加完善,為客戶端的Http程式設計提供高效、最新、功能豐富的工具包支援。
下面我們以一個簡單例子來看看如何使用HttpClient在Android客戶端訪問Web。
首先,要在你的機器上搭建一個web應用myapp,只有很簡單的一個http.jsp
內容如下:
- <%@page language="java"import="java.util.*" pageEncoding="utf-8"%>
- <html>
- <head>
- <title>
- Http Test
- </title>
- </head>
- <body>
- <%
- String type = request.getParameter("parameter");
- String result = new String(type.getBytes("iso-8859-1"),"utf-8");
- out.println("<h1>" + result + "</h1>");
- %>
- </body>
- </html>
佈局檔案:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <TextView
- android:gravity="center"
- android:id="@+id/textView"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello"
- />
- <Button android:text="get" android:id="@+id/get" android:layout_width="match_parent" android:layout_height="wrap_content"></Button>
- <Button android:text="post" android:id="@+id/post" android:layout_width="match_parent" android:layout_height="wrap_content"></Button>
- </LinearLayout>
strings.xml
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <string name="hello">通過按鈕選擇不同方式訪問網頁</string>
- <string name="app_name">Http Get</string>
- </resources>
- publicclass MainActivity extends Activity {
- private TextView textView;
- private Button get,post;
- /** Called when the activity is first created. */
- @Override
- publicvoid onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- textView = (TextView)findViewById(R.id.textView);
- get = (Button)findViewById(R.id.get);
- post = (Button)findViewById(R.id.post);
- //繫結按鈕監聽器
- get.setOnClickListener(new OnClickListener() {
- @Override
- publicvoid onClick(View v) {
- //注意:此處ip不能用127.0.0.1或localhost,Android模擬器已將它自己作為了localhost
- String uri = "http://192.168.22.28:8080/myapp/http.jsp?parameter=以Get方式傳送請求";
- textView.setText(get(uri));
- }
- });
- //繫結按鈕監聽器
- post.setOnClickListener(new OnClickListener() {
- @Override
- publicvoid onClick(View v) {
- String uri = "http://192.168.22.28:8080/myapp/http.jsp";
- textView.setText(post(uri));
- }
- });
- }
- /**
- * 以get方式傳送請求,訪問web
- * @param uri web地址
- * @return 響應資料
- */
- privatestatic String get(String uri){
- BufferedReader reader = null;
- StringBuffer sb = null;
- String result = "";
- HttpClient client = new DefaultHttpClient();
- HttpGet request = new HttpGet(uri);
- try {
- //傳送請求,得到響應
- HttpResponse response = client.execute(request);
- //請求成功
- if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
- 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 (ClientProtocolException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- finally{
- try {
- if (null != reader){
- reader.close();
- reader = null;
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if (null != sb){
- result = sb.toString();
- }
- return result;
- }
- /**
- * 以post方式傳送請求,訪問web
- * @param uri web地址
- * @return 響應資料
- */
- privatestatic String post(String uri){
- BufferedReader reader = null;
- StringBuffer sb = null;
- String result = "";
- HttpClient client = new DefaultHttpClient();
- HttpPost request = new HttpPost(uri);
- //儲存要傳遞的引數
- List<NameValuePair> params = new ArrayList<NameValuePair>();
- //新增引數
- params.add(new BasicNameValuePair("parameter","以Post方式傳送請求"));
- try {
- //設定字符集
- HttpEntity entity = new UrlEncodedFormEntity(params,"utf-8");
- //請求物件
- request.setEntity(entity);
- //傳送請求
- HttpResponse response = client.execute(request);
- //請求成功
- if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
- 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 (ClientProtocolException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- finally{
- try {
- //關閉流
- if (null != reader){
- reader.close();
- reader = null;
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if (null != sb){
- result = sb.toString();
- }
- return result;
- }
- }
執行結果如下:
3.android.net程式設計:常常使用此包下的類進行Android特有的網路程式設計,如:訪問WiFi,訪問Android聯網資訊,郵件等功能。這裡不詳細講。