一、Android網路通訊 android網路通訊一般有三種:java.net.*(標準Java介面)、org.apache介面(基於http協議)和android.net.*(Android網路介面),涉及到包括流、資料包通訊端(socket)、Internet協議、常見Http處理等。 1、使用Socket進行通訊 Socket通常也稱作"通訊端",用於描述IP地址和連接埠,是一個通訊鏈的控制代碼。Android Socket開發和JAVA Socket開發類似無非是建立一個Socket服務端和Socket用戶端進行通訊。 1 try{ 2 // 建立伺服器Socket 3 ServerSocket ss = new ServerSocket(8888); 4 System.out.println("Listening..."); 5 while(true){ 6 // 監聽是否有用戶端連上 7 Socket socket = ss.accept(); 8 System.out.println("Client Connected..."); 9 DataOutputStream dout = new DataOutputStream(socket.getOutputStream());10 Date d = new Date();11 // 示範傳送個 目前時間給用戶端12 dout.writeUTF(d.toLocaleString());13 dout.close();14 socket.close();15 }16 }17 catch(Exception e){18 e.printStackTrace();19 }20 } 1 public void connectToServer(){ //方法:串連用戶端 2 try{ 3 Socket socket = new Socket("10.0.2.2", 8888);//建立Socket對象 4 DataInputStream din = new DataInputStream(socket.getInputStream()); //獲得DataInputStream對象 5 String msg = din.readUTF(); //讀取服務端發來的訊息 6 EditText et = (EditText)findViewById(R.id.et); //獲得EditText對象 7 if (null != msg) { 8 et.setText(msg); //設定EditText對象 9 }else {10 et.setText("error data");11 }12 13 14 }15 catch(Exception e){ //捕獲並列印異常16 e.printStackTrace();17 }18 } 服務端是普通JAVA項目,先啟動服務端,再啟動用戶端Android項目,用戶端連上服務端,把目前時間資料從服務端發往用戶端顯示出來 注意:伺服器與用戶端無法連結的可能原因有:a、AndroidManifest沒有加訪問網路的許可權:<uses-permission android:name="android.permission.INTERNET"></uses-permission>b、IP地址要使用:10.0.2.2,不能用localhostc、模擬器不能配置代理 2、使用Http進行通訊 使用HttpClient在Android用戶端訪問Web,有點html知識都知道,提交表單有兩種方式get和post,Android用戶端訪問Web也是這兩種方式。在本機先建個web應用(方便示範)。data.jsp的代碼: 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> 啟動tomcat,訪問http://192.168.1.101:8080/test/data.jsp?parameter=發送的參數 注意:192.168.1.101是我原生IP,要替換成自己的IP。 複製代碼 1 //綁定按鈕監聽器 2 get.setOnClickListener(new OnClickListener() { 3 @Override 4 public void onClick(View v) { 5 //注意:此處ip不能用127.0.0.1或localhost,Android模擬器已將它自己作為了localhost 6 String uri = "http://192.168.1.101:8080/test/data.jsp?parameter=以Get方式發送請求"; 7 textView.setText(get(uri)); 8 } 9 }); 10 //綁定按鈕監聽器 11 post.setOnClickListener(new OnClickListener() { 12 @Override 13 public void onClick(View v) { 14 String uri = "http://192.168.1.101:8080/test/data.jsp"; 15 textView.setText(post(uri)); 16 } 17 }); 1 /** 2 * 以get方式發送請求,訪問web 3 * @param uri web地址 4 * @return 響應資料 5 */ 6 private static String get(String uri){ 7 BufferedReader reader = null; 8 StringBuffer sb = null; 9 String result = ""; 10 HttpClient client = new DefaultHttpClient(); 11 HttpGet request = new HttpGet(uri); 12 try { 13 //發送請求,得到響應 14 HttpResponse response = client.execute(request); 15 16 //請求成功 17 if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ 18 reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 19 sb = new StringBuffer(); 20 String line = ""; 21 String NL = System.getProperty("line.separator"); 22 while((line = reader.readLine()) != null){ 23 sb.append(line); 24 } 25 } 26 } catch (ClientProtocolException e) { 27 e.printStackTrace(); 28 } catch (IOException e) { 29 e.printStackTrace(); 30 } 31 finally{ 32 try { 33 if (null != reader){ 34 reader.close(); 35 reader = null; 36 } 37 } catch (IOException e) { 38 e.printStackTrace(); 39 } 40 } 41 if (null != sb){ 42 result = sb.toString(); 43 } 44 return result; 45 } 1 /** 2 * 以post方式發送請求,訪問web 3 * @param uri web地址 4 * @return 響應資料 5 */ 6 private static String post(String uri){ 7 BufferedReader reader = null; 8 StringBuffer sb = null; 9 String result = ""; 10 HttpClient client = new DefaultHttpClient(); 11 HttpPost request = new HttpPost(uri); 12 13 //儲存要傳遞的參數 14 List<NameValuePair> params = new ArrayList<NameValuePair>(); 15 //添加參數 16 params.add(new BasicNameValuePair("parameter","以Post方式發送請求")); 17 18 try { 19 //設定字元集 20 HttpEntity entity = new UrlEncodedFormEntity(params,"utf-8"); 21 //請求對象 22 request.setEntity(entity); 23 //發送請求 24 HttpResponse response = client.execute(request); 25 26 //請求成功 27 if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ 28 System.out.println("post success"); 29 reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 30 sb = new StringBuffer(); 31 String line = ""; 32 String NL = System.getProperty("line.separator"); 33 while((line = reader.readLine()) != null){ 34 sb.append(line); 35 } 36 } 37 } catch (ClientProtocolException e) { 38 e.printStackTrace(); 39 } catch (IOException e) { 40 e.printStackTrace(); 41 } 42 finally{ 43 try { 44 //關閉流 45 if (null != reader){ 46 reader.close(); 47 reader = null; 48 } 49 } catch (IOException e) { 50 e.printStackTrace(); 51 } 52 } 53 if (null != sb){ 54 result = sb.toString(); 55 } 56 return result; 57 } 3、擷取http網路資源 其實這裡就是前面講Android資料存放區的最後一種:網路儲存。將txt檔案和png圖片放在tomcat伺服器上,模擬器通過http路徑去擷取資源顯示出來。 擷取路徑為: 1 String stringURL = "http://192.168.1.101:8080/test/test.txt";2 String bitmapURL = "http://192.168.1.101:8080/test/crab.png"; 1 //方法,根據指定URL字串擷取網路資源 2 public void getStringURLResources(){ 3 try{ 4 URL myUrl = new URL(stringURL); 5 URLConnection myConn = myUrl.openConnection(); //開啟串連 6 InputStream in = myConn.getInputStream(); //擷取輸入資料流 7 BufferedInputStream bis = new BufferedInputStream(in);//擷取BufferedInputStream對象 8 ByteArrayBuffer baf = new ByteArrayBuffer(bis.available()); 9 int data = 0;10 while((data = bis.read())!= -1){ //讀取BufferedInputStream中資料11 baf.append((byte)data); //將資料讀取到ByteArrayBuffer中12 }13 String msg = EncodingUtils.getString(baf.toByteArray(), "GBK"); //轉換為字串,用UTF-8中文會亂碼14 EditText et = (EditText)findViewById(R.id.et); //獲得EditText對象15 et.setText(msg); //設定EditText控制項中的內容16 }17 catch(Exception e){18 e.printStackTrace();19 } 20 } 1 public void getBitmapURLResources(){ 2 try{ 3 URL myUrl = new URL(bitmapURL); //建立URL對象 4 URLConnection myConn = myUrl.openConnection(); //開啟串連 5 InputStream in = myConn.getInputStream(); //獲得InputStream對象 6 Bitmap bmp = BitmapFactory.decodeStream(in); //建立Bitmap 7 ImageView iv = (ImageView)findViewById(R.id.iv); //獲得ImageView對象 8 iv.setImageBitmap(bmp); //設定ImageView顯示的內容 9 }10 catch(Exception e){11 e.printStackTrace();12 }13 } 注意:String msg = EncodingUtils.getString(baf.toByteArray(), "GBK");//轉換為字串,用UTF-8中文會亂碼