andriod客户端与php服务器交互登录界面

客户端代码:

package com.example.app;


import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class LoginActivity extends Activity {

private Button loginBtn;  
    private Button registerBtn;  
    private EditText inputUsername;  
    private EditText inputPassword;  
    private ProgressDialog mDialog;  
    private String responseMsg = "";  
    private static final int REQUEST_TIMEOUT = 5*1000;//设置请求超时10秒钟    
    private static final int SO_TIMEOUT = 10*1000;  //设置等待数据超时时间10秒钟    

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginBtn = (Button)findViewById(R.id.login);  
        registerBtn = (Button)findViewById(R.id.register);  
        inputUsername = (EditText)findViewById(R.id.user);  
        inputPassword = (EditText)findViewById(R.id.pwd);  
                  
        //登录  
        loginBtn.setOnClickListener(new Button.OnClickListener()  
        {  
  
            @Override  
            public void onClick(View arg0) {  
                mDialog = new ProgressDialog(LoginActivity.this);  
                mDialog.setTitle("登陆");  
                mDialog.setMessage("正在登陆服务器,请稍后...");  
                mDialog.show();  
                Thread loginThread = new Thread(new LoginThread());  
                  
                loginThread.start();  
  
            }  
              
        });  
           
       // 注册
       registerBtn.setOnClickListener(new Button.OnClickListener()  
        {  
  
            @Override  
            public void onClick(View arg0) {  
                Intent intent = new Intent();  
                intent.setClass(LoginActivity.this, RegisterActivity.class);  
                startActivity(intent);  
            }  
              
        });  
   

}

private boolean loginServer(String username, String password)  
   {  
       boolean loginValidate = false;  
       //使用apache HTTP客户端实现  
       String urlStr = "http://192.168.1.111/login.php";  
       HttpPost request = new HttpPost(urlStr);  
       //如果传递参数多的话,可以对传递的参数进行封装  
       List<NameValuePair> params = new ArrayList<NameValuePair>();  
       //添加用户名和密码  
       params.add(new BasicNameValuePair("name",username));  
       params.add(new BasicNameValuePair("pwd",password));  
       try  
       {  
           //设置请求参数项  
           request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));  
           HttpClient client = getHttpClient();  
           //执行请求返回相应  
           HttpResponse response = client.execute(request);  
             
           //判断是否请求成功  
           if(response.getStatusLine().getStatusCode()==200)  
           {  
               loginValidate = true;  
               //获得响应信息  
               responseMsg = EntityUtils.toString(response.getEntity());  
           }  
       }catch(Exception e)  
       {  
           e.printStackTrace();  
       }  
       return loginValidate;  
   }  
     
    
     
   //初始化HttpClient,并设置超时  
   public HttpClient getHttpClient()  
   {  
       BasicHttpParams httpParams = new BasicHttpParams();  
       HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);  
       HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);  
       HttpClient client = new DefaultHttpClient(httpParams);  
       return client;  
   }  
 
   //Handler  
   Handler handler = new Handler()  
   {  
       public void handleMessage(Message msg)  
       {  
           switch(msg.what)  
           {  
           case 0:  
               mDialog.cancel();  
 
               Toast.makeText(getApplicationContext(), "登录成功!", Toast.LENGTH_SHORT).show();  
               /*Intent intent = new Intent();  
       intent.setClass(LoginActivity.this, MainActivity.class);  
               startActivity(intent);  */
               finish();  
               break;  
           case 1:  
               mDialog.cancel();  
               Toast.makeText(getApplicationContext(), "密码错误", Toast.LENGTH_SHORT).show();  
               break;  
           case 2:  
               mDialog.cancel();  
               Toast.makeText(getApplicationContext(), "URL验证失败", Toast.LENGTH_SHORT).show();  
               break;  
             
           }  
             
       }  
   };  
     
   //LoginThread线程类  
   class LoginThread implements Runnable  
   {  
 
       @Override  
       public void run() {  
           String username = inputUsername.getText().toString();  
           String password = inputPassword.getText().toString();     
                 
           //URL合法,但是这一步并不验证密码是否正确  
           boolean loginValidate = loginServer(username, password);  
           Message msg = handler.obtainMessage();  
           if(loginValidate)  
           {  
               if(responseMsg.equals("success"))  
               {  
                   msg.what = 0;  
                   handler.sendMessage(msg);  
               }else  
               {  
                   msg.what = 1;  
                   handler.sendMessage(msg);  
               }  
                 
           }else  
           {  
               msg.what = 2;  
               handler.sendMessage(msg);  
           }  
       }  
         
   }  

}

服务器代码:

conn.php:

<?php
$dbhost = "localhost";
$dbuser = "root"; //我的用户名
$dbpass = "sa"; //我的密码
$dbname = "smarttravel"; //我的mysql库名
$cn = mysql_connect($dbhost,$dbuser,$dbpass) or die("connect error");
@mysql_select_db($dbname)or die("db error");
mysql_query("set names 'UTF-8'");
?>

login.php:

<?php
error_reporting(E_ALL ^ E_NOTICE);
include ("conn.php");//连接数据库
$username=str_replace(" ","",$_POST['name']);//接收客户端发来的username;
$sql="select * from users where name='$username'";
$query=mysql_query($sql);
$rs = mysql_fetch_array($query);if(is_array($rs)){
if($_POST['pwd']==$rs['password']){
echo "success";
}else{
echo "error";
}
}
?>

lyout.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
    
    <LinearLayout android:layout_width="fill_parent"  
                  android:layout_height="wrap_content">  
        <TextView android:layout_width="wrap_content"  
                  android:layout_height="wrap_content"  
                  android:text="账号:"/>  
        <EditText android:layout_width="240dip"  
                  android:layout_height="wrap_content"  
                  android:text=""  
                  android:id="@+id/user"/>  
    </LinearLayout>  
    
    
     <LinearLayout android:layout_width="fill_parent"  
                  android:layout_height="wrap_content">  
        <TextView android:layout_width="wrap_content"  
                  android:layout_height="wrap_content"  
                  android:text="密码:"/>  
        <EditText android:layout_width="240dip"  
                  android:layout_height="wrap_content"  
                  android:password="true"  
                  android:id="@+id/pwd"/>  
    </LinearLayout>  
    
     
    <LinearLayout  
        android:layout_width="fill_parent"  
        android:layout_height="fill_parent"  
        android:orientation="horizontal" >  
        
        <LinearLayout
            android:layout_width="142dp"
            android:layout_height="342dp"
            android:orientation="vertical" >
  
            <CheckBox  
                android:id="@+id/checkbox"  
                android:layout_width="wrap_content"  
                android:layout_height="wrap_content"  
                android:text="记住密码" />


            <Button
                android:id="@+id/login"
                android:layout_width="135dp"
                android:layout_height="40dp"
                android:text="登录" />
  
        </LinearLayout>  
       
         <LinearLayout
             android:layout_width="142dp"
             android:layout_height="342dp"
             android:orientation="vertical" >
  
            <CheckBox  
                android:id="@+id/checkbox1"  
                android:layout_width="wrap_content"  
                android:layout_height="wrap_content"  
                android:text="自动登录" />


            <Button
                android:id="@+id/register"
                android:layout_width="135dp"
                android:layout_height="40dp"
                android:text="注册" />
  
        </LinearLayout>  
        
      
        
    </LinearLayout>  
    
    
</LinearLayout>  



AndroidManifest.xml:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.app"
    android:versionCode="1"
    android:versionName="1.0" >


    <!-- <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" /> -->


    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.app.LoginActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />


                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值