安卓服务端开发(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() {
			@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("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 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 不了解请,到这里看一下:

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

如有其他疑问请留言,一定尽快解答。

你可能感兴趣的:(安卓服务端开发,php服务器脚本)