Android客戶端向服務器端傳值——登陸實現

根據實習科目需求,先完成Android客戶端的登陸功能。java

要實現登陸必然涉及到客戶端與服務器端的交互,即客戶端須要將用戶輸入的帳號和密碼傳給服務器端,服務器端鏈接數據庫對其進行驗證。web

細化問題,先研究一下客戶端向服務器端傳值的方法。。數據庫

新建一個web工程,建一個Servlet以下:服務器

public class UserServlet extends HttpServlet {  
    private static final long serialVersionUID = 1L;     
    public UserServlet() {  
        super();  
    }  
    public void doGet(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        String userName=request.getParameter("userName");  
        String passWord=request.getParameter("passWord");  
        //在服務器端解決中文亂碼問題  
        userName=NewString.getNewString(userName);  
        passWord=NewString.getNewString(passWord);  
        System.out.println("帳號:"+userName);  
        System.out.println("密碼:"+passWord);   
    }     
    protected void doPost(HttpServletRequest request,  
            HttpServletResponse response) throws ServletException, IOException {  
        this.doGet(request, response);  
    }  
}

客戶端登陸界面以下,佈局比較簡單。app

Activity代碼ide

public class LoginActivity extends Activity {
    private EditText userName;
	private EditText passWord;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);        
        userName=(EditText)this.findViewById(R.id.userName);
        passWord=(EditText)this.findViewById(R.id.passWord);       
    }
     /**
      * 用戶登陸的方法
      */
    public void login(View v)
    {  
    	//取得用戶輸入的帳號和密碼
    	String name=userName.getText().toString();
    	String pass=passWord.getText().toString();
    	boolean result=UserService.check(name,pass);
    	if(result)
    	{
    		Toast.makeText(getApplicationContext(),R.string.success,1).show();
    	}else
    	{
    		Toast.makeText(getApplicationContext(),R.string.fail,1).show();
    	}  	
    }
}

具體實現的工具類:工具

public class UserService {
	/**
	 * 驗證用戶登陸是否合法
	 * 返回值:請求是否成功
	 */
	public static boolean check(String name, String pass) {
		String path="http://135.32.89.17:8080/lss/UserServlet";
		//將用戶名和密碼放入HashMap中
		Map<String,String> params=new HashMap<String,String>();
		params.put("userName", name);
		params.put("passWord", pass);		
		try {
			return sendGETRequest(path,params,"UTF-8");
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
	private static boolean sendGETRequest(String path,
		Map<String, String> params,String encode) throws MalformedURLException, IOException {
		StringBuilder url=new StringBuilder(path);
		url.append("?");
		for(Map.Entry<String, String> entry:params.entrySet())
		{
			url.append(entry.getKey()).append("=");
			url.append(URLEncoder.encode(entry.getValue(),encode));
			url.append("&");
		}
		//刪掉最後一個&
		url.deleteCharAt(url.length()-1);
        HttpURLConnection conn=(HttpURLConnection)new URL(url.toString()).openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        if(conn.getResponseCode()==200)
         {
    	   return true;
         }
		   return false;
	     }
}

運行結果
佈局

服務端接收內容:ui

總結:this

客戶端的工具類將用戶輸入的帳號和密碼放入HashMap當中,循環遍歷取出HashMap中的鍵和值,構造出形如

http://www.xxx.xxx?key1=value1&key2=value2的字符串。利用該字符串鏈接服務器,傳送相關值。

相關文章
相關標籤/搜索