Android平臺有三種網絡接口可使用,他們分別是:java.net.*(標準Java接口)、Org.apache接口和Android.net.*(Android網絡接口)。下面分別介紹這些接口的功能和做用。html
1.標準Java接口
java.net.*提供與聯網有關的類,包括流、數據包套接字(socket)、Internet協議、常見Http處理等。好比:建立URL,以及URLConnection/HttpURLConnection對象、設置連接參數、連接到服務器、向服務器寫數據、從服務器讀取數據等通訊。這些在Java網絡編程中均有涉及,咱們看一個簡單的socket編程,實現服務器回發客戶端信息。
服務端:java
1 public class Server implements Runnable{ 2 @Override 3 public void run() { 4 Socket socket = null; 5 try { 6 ServerSocket server = new ServerSocket(18888); 7 //循環監聽客戶端連接請求 8 while(true){ 9 System.out.println("start..."); 10 //接收請求 11 socket = server.accept(); 12 System.out.println("accept..."); 13 //接收客戶端消息 14 BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 15 String message = in.readLine(); 16 //發送消息,向客戶端 17 PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true); 18 out.println("Server:" + message); 19 //關閉流 20 in.close(); 21 out.close(); 22 } 23 } catch (IOException e) { 24 e.printStackTrace(); 25 }finally{ 26 if (null != socket){ 27 try { 28 socket.close(); 29 } catch (IOException e) { 30 e.printStackTrace(); 31 } 32 } 33 } 34 35 } 36 //啓動服務器 37 public static void main(String[] args){ 38 Thread server = new Thread(new Server()); 39 server.start(); 40 } 41 }
客戶端,MainActivityandroid
1 public class MainActivity extends Activity { 2 private EditText editText; 3 private Button button; 4 /** Called when the activity is first created. */ 5 @Override 6 public void onCreate(Bundle savedInstanceState) { 7 super.onCreate(savedInstanceState); 8 setContentView(R.layout.main); 9 10 editText = (EditText)findViewById(R.id.editText1); 11 button = (Button)findViewById(R.id.button1); 12 13 button.setOnClickListener(new OnClickListener() { 14 @Override 15 public void onClick(View v) { 16 Socket socket = null; 17 String message = editText.getText().toString()+ "\r\n" ; 18 try { 19 //建立客戶端socket,注意:不能用localhost或127.0.0.1,Android模擬器把本身做爲localhost 20 socket = new Socket("<span style="font-weight: bold;">10.0.2.2</span>",18888); 21 PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter 22 (socket.getOutputStream())),true); 23 //發送數據 24 out.println(message); 25 26 //接收數據 27 BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 28 String msg = in.readLine(); 29 if (null != msg){ 30 editText.setText(msg); 31 System.out.println(msg); 32 } 33 else{ 34 editText.setText("data error"); 35 } 36 out.close(); 37 in.close(); 38 } catch (UnknownHostException e) { 39 e.printStackTrace(); 40 } catch (IOException e) { 41 e.printStackTrace(); 42 } 43 finally{ 44 try { 45 if (null != socket){ 46 socket.close(); 47 } 48 } catch (IOException e) { 49 e.printStackTrace(); 50 } 51 } 52 } 53 }); 54 } 55 }
佈局文件:web
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:orientation="vertical" android:layout_width="fill_parent" 4 android:layout_height="fill_parent"> 5 <TextView android:layout_width="fill_parent" 6 android:layout_height="wrap_content" android:text="@string/hello" /> 7 <EditText android:layout_width="match_parent" android:id="@+id/editText1" 8 android:layout_height="wrap_content" 9 android:hint="input the message and click the send button" 10 ></EditText> 11 <Button android:text="send" android:id="@+id/button1" 12 android:layout_width="fill_parent" android:layout_height="wrap_content"></Button> 13 </LinearLayout>
啓動服務器:apache
1 javac com/test/socket/Server.java 2 java com.test.socket.Server
運行客戶端程序:編程
結果如圖:服務器
注意:服務器與客戶端沒法連接的可能緣由有:
沒有加訪問網絡的權限:<uses-permission android:name="android.permission.INTERNET"></uses-permission>
IP地址要使用:10.0.2.2
模擬器不能配置代理。網絡
2。Apache接口app
對於大部分應用程序而言JDK自己提供的網絡功能已遠遠不夠,這時就須要Android提供的Apache HttpClient了。它是一個開源項目,功能更加完善,爲客戶端的Http編程提供高效、最新、功能豐富的工具包支持。
下面咱們以一個簡單例子來看看如何使用HttpClient在Android客戶端訪問Web。
首先,要在你的機器上搭建一個web應用myapp,只有很簡單的一個http.jsp
內容以下:socket
1 <%@page language="java" import="java.util.*" pageEncoding="utf-8"%> 2 <html> 3 <head> 4 <title> 5 Http Test 6 </title> 7 </head> 8 <body> 9 <% 10 String type = request.getParameter("parameter"); 11 String result = new String(type.getBytes("iso-8859-1"),"utf-8"); 12 out.println("<h1>" + result + "</h1>"); 13 %> 14 </body> 15 </html>
而後實現Android客戶端,分別以post、get方式去訪問myapp,代碼以下:
佈局文件:
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:orientation="vertical" 4 android:layout_width="fill_parent" 5 android:layout_height="fill_parent" 6 > 7 <TextView 8 android:gravity="center" 9 android:id="@+id/textView" 10 android:layout_width="fill_parent" 11 android:layout_height="wrap_content" 12 android:text="@string/hello" 13 /> 14 <Button android:text="get" android:id="@+id/get" android:layout_width="match_parent" android:layout_height="wrap_content"></Button> 15 <Button android:text="post" android:id="@+id/post" android:layout_width="match_parent" android:layout_height="wrap_content"></Button> 16 </LinearLayout>
資源文件:
strings.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <resources> 3 <string name="hello">經過按鈕選擇不一樣方式訪問網頁</string> 4 <string name="app_name">Http Get</string> 5 </resources>
主Activity:
1 public class MainActivity extends Activity { 2 private TextView textView; 3 private Button get,post; 4 /** Called when the activity is first created. */ 5 @Override 6 public void onCreate(Bundle savedInstanceState) { 7 super.onCreate(savedInstanceState); 8 setContentView(R.layout.main); 9 10 textView = (TextView)findViewById(R.id.textView); 11 get = (Button)findViewById(R.id.get); 12 post = (Button)findViewById(R.id.post); 13 14 //綁定按鈕監聽器 15 get.setOnClickListener(new OnClickListener() { 16 @Override 17 public void onClick(View v) { 18 //注意:此處ip不能用127.0.0.1或localhost,Android模擬器已將它本身做爲了localhost 19 String uri = "http://192.168.22.28:8080/myapp/http.jsp?parameter=以Get方式發送請求"; 20 textView.setText(get(uri)); 21 } 22 }); 23 //綁定按鈕監聽器 24 post.setOnClickListener(new OnClickListener() { 25 @Override 26 public void onClick(View v) { 27 String uri = "http://192.168.22.28:8080/myapp/http.jsp"; 28 textView.setText(post(uri)); 29 } 30 }); 31 } 32 /** 33 * 以get方式發送請求,訪問web 34 * @param uri web地址 35 * @return 響應數據 36 */ 37 private static String get(String uri){ 38 BufferedReader reader = null; 39 StringBuffer sb = null; 40 String result = ""; 41 HttpClient client = new DefaultHttpClient(); 42 HttpGet request = new HttpGet(uri); 43 try { 44 //發送請求,獲得響應 45 HttpResponse response = client.execute(request); 46 47 //請求成功 48 if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ 49 reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 50 sb = new StringBuffer(); 51 String line = ""; 52 String NL = System.getProperty("line.separator"); 53 while((line = reader.readLine()) != null){ 54 sb.append(line); 55 } 56 } 57 } catch (ClientProtocolException e) { 58 e.printStackTrace(); 59 } catch (IOException e) { 60 e.printStackTrace(); 61 } 62 finally{ 63 try { 64 if (null != reader){ 65 reader.close(); 66 reader = null; 67 } 68 } catch (IOException e) { 69 e.printStackTrace(); 70 } 71 } 72 if (null != sb){ 73 result = sb.toString(); 74 } 75 return result; 76 } 77 /** 78 * 以post方式發送請求,訪問web 79 * @param uri web地址 80 * @return 響應數據 81 */ 82 private static String post(String uri){ 83 BufferedReader reader = null; 84 StringBuffer sb = null; 85 String result = ""; 86 HttpClient client = new DefaultHttpClient(); 87 HttpPost request = new HttpPost(uri); 88 89 //保存要傳遞的參數 90 List<NameValuePair> params = new ArrayList<NameValuePair>(); 91 //添加參數 92 params.add(new BasicNameValuePair("parameter","以Post方式發送請求")); 93 94 try { 95 //設置字符集 96 HttpEntity entity = new UrlEncodedFormEntity(params,"utf-8"); 97 //請求對象 98 request.setEntity(entity); 99 //發送請求 100 HttpResponse response = client.execute(request); 101 102 //請求成功 103 if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ 104 System.out.println("post success"); 105 reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 106 sb = new StringBuffer(); 107 String line = ""; 108 String NL = System.getProperty("line.separator"); 109 while((line = reader.readLine()) != null){ 110 sb.append(line); 111 } 112 } 113 } catch (ClientProtocolException e) { 114 e.printStackTrace(); 115 } catch (IOException e) { 116 e.printStackTrace(); 117 } 118 finally{ 119 try { 120 //關閉流 121 if (null != reader){ 122 reader.close(); 123 reader = null; 124 } 125 } catch (IOException e) { 126 e.printStackTrace(); 127 } 128 } 129 if (null != sb){ 130 result = sb.toString(); 131 } 132 return result; 133 } 134 }
運行結果以下:
3.android.net編程:
經常使用此包下的類進行Android特有的網絡編程,如:訪問WiFi,訪問Android聯網信息,郵件等功能。這裏不詳細講。
參考原文:http://blog.csdn.net/yuzhiboyi/article/details/7743390