安卓服務端開發(1) 安卓結合PHP實現連接伺服器驗證登錄功能(附全部代碼)

啥都不說瞭,直接上代碼。如果看不懂在下面和我留言。

先看服務端:使用PHP語言,部署在新浪sae伺服器(自帶伺服器)

將一下所有php文件放在同一個目錄下:

1.db.php 封裝好的用於連接伺服器的類

'127.0.0.1',  
        'user'=>'root',  
        'password'=>'',  
        'database'=>'value'  
    ); */ 
    private function _construct(){  
        
    }  
  
    static public function getInstance(){  
        //如果沒有實例,則創建, 然後返回已創建的實例  
         if(!(self::$_instance instanceof self)){  
          self::$_instance =new self();  
         }   
         return self::$_instance;  
    }  
    public function connect(){  
        if(!self::$_connectSource){  
           self::$_connectSource=mysql_connect(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS); 
		   //self::$_connectSource = @mysql_connect($this->_dbConfig['host'], $this->_dbConfig['user'], $this->_dbConfig['password']);	
        if(!self::$_connectSource){ 
			//如果伺服器連接不成功
			//拋出異常,在調用該connnect()函數時,通過try catch 進行捕獲
			throw new Exception ('mysql connect error'.mysql_error);
       //die('mysql connect error'.mysql_error);  
    }  
     mysql_select_db(SAE_MYSQL_DB,self::$_connectSource);  
	 //mysql_select_db($this->_dbConfig['database'], self::$_connectSource);
     mysql_query("set names UTF8",self::$_connectSource);  
        }  
     return self::$_connectSource;  
    }  
  
}  

2.response.php 用於封裝通信數據(json或者xml)

 $code,
			'message' => $message,
			'data' => $data,
		);

		if($type == 'json') {
			self::json($code, $message, $data);
			exit;
		} elseif($type == 'array') {
			var_dump($result);
		} elseif($type == 'xml') {
			self::xmlEncode($code, $message, $data);
			exit;
		} else {
			// TODO
		}
	}
    
	/**
	* 按json方式輸出通信數據
	* @param integer $code 狀態碼
	* @param string $message 提示信息
	* @param array $data 數據
	* return string
	*/
	public static function json($code, $message = '', $data = array()) {
		
		if(!is_numeric($code)) {
			return '';
		}

		$result = array(
			'code' => $code,
			'message' => $message,
			'data' => $data
		);

		echo json_encode($result);
		exit;
	}

	/**
	* 按xml方式輸出通信數據
	* @param integer $code 狀態碼
	* @param string $message 提示信息
	* @param array $data 數據
	* return string
	*/
	public static function xmlEncode($code, $message, $data = array()) {
		if(!is_numeric($code)) {
			return '';
		}

		$result = array(
			'code' => $code,
			'message' => $message,
			'data' => $data,
		);

		//header("Content-Type:text/xml");
		$xml = "\n";
		$xml .= "\n";

		$xml .= self::xmlToEncode($result);

		$xml .= "";
		echo $xml;
	}

	public static function xmlToEncode($data) {

		$xml = $attr = "";
		foreach($data as $key => $value) {
			if(is_numeric($key)) {
				$attr = " id='{$key}'";
				$key = "item";
			}
			$xml .= "";
			$xml .= is_array($value) ? self::xmlToEncode($value) : $value;
			$xml .= "\n";
		}
		return $xml;
	}

}

3.checklogin.php 提供給客戶端 ,讓客戶端使用GET請求,傳入username,passwd 驗證登錄

connect(); 
}catch(Exception $e){
    Response::show(403,'伺服器連接失敗'); 
}

$result=mysql_query($sql,$connect);
$videos=array();
//mysql_fetch_assoc()字段名key植是value,方便客戶端解析。每行獲取,區別與mysql_fetch_array()
while($video=mysql_fetch_assoc($result)){
$videos[]=$video;
}
//這樣就從伺服器中獲取瞭數據存到瞭$videos[]中,接著需要轉換成接口數據
if($videos){
Response::show(200,'首頁數據獲取成功',$videos);
//這樣默認生成瞭json數據,如果需要xml數據,需要在訪問時https://...com/list.php?format=xml
}else{
Response::show(400,'首頁數據獲取失敗',$videos);
}

————————————————————————————————————————————————————

到這裡服務端代碼已經完成,接受客戶端的hhtp get請求,通過查詢伺服器,驗證用戶名,密碼是否正確。將結果封裝成json或者xml,輸出在瀏覽器中。供客戶端讀取。

下面是安卓客戶端部分代碼:

佈局文件就不展示瞭,就是兩個textview 和兩個edittext,還有一個Button

直接上MainActivity.java

package com.example.bee;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

 

public class Login extends Activity {

	/**
	 * 用於登錄的界面
	 */
	String result="",user,passwd;
	Handler myhandler;
    EditText userview,passwdview;
    Button login,register;
    Thread t;
    SharedPreferences sp;
    int code;
    String realname;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        userview=(EditText) findViewById(R.id.login_edt_user);
        passwdview=(EditText) findViewById(R.id.login_edt_passwd);
        login=(Button) findViewById(R.id.btn_login);
        register=(Button) findViewById(R.id.btn_register);
        sp=getSharedPreferences("login", MODE_PRIVATE);
        String getname=sp.getString("username", null);
		if(getname==null)
		{
			Toast.makeText(Login.this, "sp null", 0).show();
		}else{
			Toast.makeText(Login.this, "sp have", 0).show();
			userview.setText(sp.getString("username", null));
			passwdview.setText(sp.getString("passwd", null));
		}
		
        //登陸按鈕點擊事件
         login.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				  
		         t=new Thread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						try {
							user=userview.getText().toString();
							passwd=passwdview.getText().toString();
							URL url=new URL("https://luo.sinaapp.com/e/checklogin.php?username="+user+"&passwd="+passwd);
							HttpURLConnection urlConnection=(HttpURLConnection) url.openConnection();
							InputStreamReader isr=new InputStreamReader(urlConnection.getInputStream());
							BufferedReader br=new BufferedReader(isr);
							result=br.readLine(); 
							//對獲得的json數據進行解析
							try {
								 JSONObject object=new JSONObject(result);
							     code=object.getInt("code");
							     JSONArray ja=  object.getJSONArray("data");
							     String data=ja.getString(0);
							     JSONObject secondobject=new JSONObject(data);
							     realname=secondobject.getString("realname");
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							Message m1=myhandler.obtainMessage();
							if(code==400)//登錄失敗
							{
								m1.what=1;
								myhandler.sendMessage(m1);
							}else if(code==200){//登錄成功
								m1.what=2;
								myhandler.sendMessage(m1);
							}else{//其他情況:聯網失敗,伺服器異常等
								m1.what=3;
								myhandler.sendMessage(m1);
							}
							
						} catch (MalformedURLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});
				t.start();
			}
		}); 
      //註冊點擊事件
        /*register.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i=new Intent(Login.this,RegisterActivity.class);
				startActivity(i);
				
			}
		});*/
        myhandler=new Handler(){
        	@Override
        	public void handleMessage(Message msg) {
        		// TODO Auto-generated method stub
        		super.handleMessage(msg);
        		if(msg.what==1){
        		Toast.makeText(Login.this, "用戶名或密碼不正確", 0).show();
        		} else if(msg.what==2){
        			Toast.makeText(Login.this, "歡迎您:"+realname, 0).show();
        			/*登陸成功將數據寫到本地保存下來,以便下次自動額登陸*/
					sp=getSharedPreferences("login", MODE_PRIVATE);
					Editor editor=sp.edit();
					editor.putString("username", user);
					editor.putString("passwd", passwd);
					editor.putString("realname", realname);
					editor.commit();
					Intent i = new Intent(Login.this, MainActivity.class);
					startActivity(i);
					finish();
        		} else {
        			Toast.makeText(Login.this, "網絡連接失敗", 0).show();
        		}
        	}
        };
       
        
    }


}

如果對上面的sharedpreference 不瞭解請,到這裡看一下:

https://blog.csdn.net/davidluo001/article/details/42290369

如有其他疑問請留言,一定盡快解答。

發佈留言