一、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,不能用localhost
c、模擬器不能配置代理
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中文會亂碼