安卓服務端開發(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 .= "<{$key}{$attr}>";$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資料,需要在訪問時http://...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() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stub t=new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubtry {user=userview.getText().toString();passwd=passwdview.getText().toString();URL url=new URL("http://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 blocke.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 blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}});t.start();}}); //註冊點擊事件 /*register.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubIntent 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 不瞭解請,到這裡看一下:
http://blog.csdn.net/davidluo001/article/details/42290369
如有其他疑問請留言,一定儘快解答。
http://www.bkjia.com/PHPjc/941437.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/941437.htmlTechArticle安卓服務端開發(1) 安卓結合PHP實現串連資料庫驗證登入功能(附全部代碼) 啥都不說了,直接上代碼。如果看不懂在下面和我留言。...