Android作爲客戶端,PC作爲服務端:實現網絡通信


此項目實現網絡通信,android手機客戶端去請求PC服務端,將PCmysql中的數據顯示在手機上。

   PC服務端用JavaWeb寫了個servletandroid手機客戶端請求這個servlet,由servlet執行查詢數據,並返回給手機客戶端,服務器爲Tomcat

  爲了更清楚的展示,咱們現在mysql建一個測試表test

 

[plain] view plaincopy
  1. create table test(  
  2. name varchar(20) primary key  
  3. );  

插入幾條記錄,我們這裏插入漢字,遇到亂碼,我們可以去解決。

[plain] view plaincopy
  1. insert into test values('張三');  
  2. insert into test values('李四');  
  3. insert into test values('王五');  


 

插入成功

 

閒話少說,直接上代碼:

 

 

PC服務端

  我用MyEclipse建立了一個JavaWeb項目,這個項目中主要由一個數據查詢類DBManager.java和一個servlet(loadMessage.java)組成

 

DBManager.java

[plain] view plaincopy
  1. package com.njue.DBManager;  
  2.   
  3. import java.awt.List;  
  4. import java.sql.*;  
  5. import java.util.ArrayList;  
  6.   
  7. import org.omg.CORBA.Object;  
  8.   
  9. public class DBManager {  
  10.     ;  
  11.     String userName="root";  
  12.     String password="123456";  
  13.     Connection conn=null;  
  14.     Statement stmt=null;  
  15.     String url="jdbc:mysql://localhost:3306/mysql";  
  16.     ArrayList<String> list=new ArrayList<String>();  
  17.     String sql;  
  18. public DBManager(){  
  19.     sql="select * from test;";  
  20.     try {  
  21.         Class.forName("com.mysql.jdbc.Driver");  
  22.         conn=DriverManager.getConnection(url,userName,password);  
  23.         stmt=conn.createStatement();  
  24.         ResultSet rst=stmt.executeQuery(sql);  
  25.         while(rst.next()){  
  26.             //String name=new   String(rst.getString("name").getBytes("latin1"), "UTF-8");   
  27.             String name=new   String(rst.getString("name").getBytes("latin1"), "GB2312");// 這句可要可不要,以你不出現亂碼爲準  
  28.             //也可不用轉化,直接寫成String name=rst.getString("name");  
  29.             list.add(name);  
  30.               
  31.         }  
  32.         rst.close();  
  33.     } catch (Exception e) {  
  34.         // TODO Auto-generated catch block  
  35.         e.printStackTrace();  
  36.     }  
  37. }  
  38. public ArrayList<String> getList(){  
  39.     return list;  
  40.     }  
  41. }  


 

loadMessage.java

[plain] view plaincopy
  1. package com.amaker.servlet;  
  2.   
  3. import java.awt.List;  
  4. import java.io.IOException;  
  5. import java.io.PrintWriter;  
  6. import java.util.ArrayList;  
  7.   
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.http.HttpServlet;  
  10. import javax.servlet.http.HttpServletRequest;  
  11. import javax.servlet.http.HttpServletResponse;  
  12.   
  13. import com.njue.DBManager.DBManager;  
  14.   
  15. public class loadMessage extends HttpServlet {  
  16.     public loadMessage() {  
  17.         super();  
  18.     }  
  19.     public void destroy() {  
  20.         super.destroy(); // Just puts "destroy" string in log  
  21.         // Put your code here  
  22.     }  
  23.        
  24.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  25.             throws ServletException, IOException {  
  26.     //  request.setCharacterEncoding("UTF-8");  
  27.         response.setContentType("text/html; charset=UTF-8" );  
  28.         PrintWriter out = response.getWriter();  
  29.          String message="";  
  30.          DBManager db=new DBManager();  
  31.            ArrayList<String> list=db.getList();  
  32.            for(int i=0;i<list.size();i++){  
  33.                message=message+list.get(i)+"\r\n";  
  34.            }  
  35.         out.print(message);  
  36.         out.flush();  
  37.         out.close();  
  38.     }  
  39.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  40.             throws ServletException, IOException {  
  41.         doGet(request,response);  
  42.   
  43.     }  
  44.     public void init() throws ServletException {  
  45.         // Put your code here  
  46.     }  
  47.   
  48. }  

 

 

Android手機客戶端代碼:

AndroidClientActivity.java

[plain] view plaincopy
  1. package com.njue.androidClient;  
  2. import android.app.Activity;  
  3. import android.os.Bundle;  
  4. import android.widget.TextView;  
  5.   
  6. public class AndroidClientActivity extends Activity {  
  7.     /** Called when the activity is first created. */  
  8.     @Override  
  9.     public void onCreate(Bundle savedInstanceState) {  
  10.         super.onCreate(savedInstanceState);  
  11.         setContentView(R.layout.main);  
  12.         TextView tv=(TextView)findViewById(R.id.tv);  
  13.         // 查詢返回結果  
  14.         String result = HttpUtil.queryStringForPost("http://10.0.2.2:8080/androidWeb/servlet/loadMessage");  
  15.         //String result = HttpUtil.queryStringForPost("http://122.88.34.123:8080/androidWeb/servlet/loadMessage");  
  16.         tv.setText(result);  
  17.     }  
  18. }  


 

HttpUtil.java

[plain] view plaincopy
  1. package com.njue.androidClient;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import org.apache.http.HttpResponse;  
  6. import org.apache.http.client.ClientProtocolException;  
  7. import org.apache.http.client.methods.HttpGet;  
  8. import org.apache.http.client.methods.HttpPost;  
  9. import org.apache.http.impl.client.DefaultHttpClient;  
  10. import org.apache.http.util.EntityUtils;  
  11.   
  12. public class HttpUtil {  
  13.     // 基礎URL  
  14.     // 獲得Get請求對象request  
  15.     public static HttpGet getHttpGet(String url){  
  16.         HttpGet request = new HttpGet(url);  
  17.          return request;  
  18.     }  
  19.     // 獲得Post請求對象request  
  20.     public static HttpPost getHttpPost(String url){  
  21.          HttpPost request = new HttpPost(url);  
  22.          return request;  
  23.     }  
  24.     // 根據請求獲得響應對象response  
  25.     public static HttpResponse getHttpResponse(HttpGet request) throws ClientProtocolException, IOException{  
  26.         HttpResponse response = new DefaultHttpClient().execute(request);  
  27.         return response;  
  28.     }  
  29.     // 根據請求獲得響應對象response  
  30.     public static HttpResponse getHttpResponse(HttpPost request) throws ClientProtocolException, IOException{  
  31.         HttpResponse response = new DefaultHttpClient().execute(request);  
  32.         return response;  
  33.     }  
  34.       
  35.     // 發送Post請求,獲得響應查詢結果  
  36.     public static String queryStringForPost(String url){  
  37.         // 根據url獲得HttpPost對象  
  38.         HttpPost request = HttpUtil.getHttpPost(url);  
  39.         String result = null;  
  40.         try {  
  41.             // 獲得響應對象  
  42.             HttpResponse response = HttpUtil.getHttpResponse(request);  
  43.             // 判斷是否請求成功  
  44.             if(response.getStatusLine().getStatusCode()==200){  
  45.                 // 獲得響應  
  46.                 result = EntityUtils.toString(response.getEntity());  
  47.                  //result=new  String(result.getBytes("8859_1"),"GB2312");  這句可要可不要,以你不出現亂碼爲準  
  48.   
  49.   
  50.                 return result;  
  51.             }  
  52.         } catch (ClientProtocolException e) {  
  53.             e.printStackTrace();  
  54.             result = "網絡異常!";  
  55.             return result;  
  56.         } catch (IOException e) {  
  57.             e.printStackTrace();  
  58.             result = "網絡異常!";  
  59.             return result;  
  60.         }  
  61.         return null;  
  62.     }  
  63. }  


 

當然還得在AndroidManifest.xml中加入網絡訪問權限:

[plain] view plaincopy
  1. <uses-permission android:name="android.permission.INTERNET"></uses-permission>  


 

需要注意的寫服務器的主機號時,千萬不能寫localhost或者127.0.0.1,因爲Android模擬器雖然和服務端程序在同一臺電腦上,但兩個畢竟是獨立的系統,我們可以用10.0.2.2去訪問本機。

 

運行結果:

 

這是在模擬器上運行,有的同學有這樣的想法,把ip改成自己電腦真實的Ip,把客戶端拿到真機上去實驗,但運行後會發現會顯示“網絡異常”,不能訪問。這裏涉及到了網絡方面的問題,其實也非常簡單。下篇博客將會詳細的講解,去解決這個問題。

 

 

 補充:上傳兩個項目,不禁可以訪問mysql,也可以訪問Access數據庫。

下載地址:http://download.csdn.net/detail/pzhtpf/4388157

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章