4

我是android开发的新手。我想使用 php mysql 和 json 进行登录验证。

我只负责 PHP、MySql 和 json 部分。

如果用户在 android app 中输入用户名和密码,则需要使用 PHP 和 Mysql 检查用户表,并且只需要使用 json 发送 1 或 0 之类的状态码。

如果用户名和密码匹配,则 status = 1 需要发送到 android app 编码,否则为 0。

状态检查过程需要在 Android Coding 部分完成。

如果 status = 1 并且我需要重定向到 android app 中的另一个窗口。

我看过很多 tuts,但没有任何帮助。

所以,请帮助我如何将状态PHP 发送到 android 应用程序以及如何获取该状态并在 android 中验证

4

3 回答 3

3

我已经为我的项目完成了这段代码。它工作正常。试试看。

登录2.php

<?php
$un=$_POST['username'];
$pw=$_POST['password'];
//connect to the db

$host="localhost"; // Host name 
$user="root"; // Mysql username 
$pswd=""; // Mysql password 
$db="database_name"; // Database name 
$tbl_name="user_info"; // Table name

$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db, $conn);
//run the query to search for the username and password the match
//$query = "SELECT * FROM $tbl_name WHERE first_name = '$un' AND password = '$pw'";
$query = "SELECT emp_id FROM $tbl_name WHERE first_name = '$un' AND password = '$pw'";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
//this is where the actual verification happens
if(mysql_num_rows($result) > 0)
echo mysql_result($result,0);  // for correct login response
else
echo 0; // for incorrect login response
?>

Android login.java 的 Java 代码

取两个edittext和按钮,然后在按钮上单击放置此代码。如果您不想将用户名、emp_id 保存到整个应用程序,请删除 saveperference 方法。

    @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
                    postParameters.add(new BasicNameValuePair("username", username
                            .getText().toString()));
                    postParameters.add(new BasicNameValuePair("password", password
                            .getText().toString()));
                    // String valid = "1";
                    String response = null;
                    try {
                        // "http://10.0.2.2//Mobile/login2.php"
                        response = CustomHttpClient
                                .executeHttpPost(
                                        "http://10.0.2.2//Mobile/login2.php",
                                        postParameters);
// now in result you will have the response from php file either 0 or 1.                        
result = response.toString();
                        // res = res.trim();
                        result = result.replaceAll("\\s+", "");
                        // error.setText(res);

                        if (!result.equals("0")) {
                            SavePreferences("name", "pass", "emp_id", username
                                    .getText().toString(), password.getText()
                                    .toString());
                            Intent in = new Intent(Login.this, MainScreen.class);

                            // LoadPreferences();
                            error.setText("");

                            startActivity(in);
                        }

                        else
                            error.setText("Incorrect Username or Password");

                    } catch (Exception e) {
                        // un.setText(e.toString());
                    }

                }

CustomHttpClient.java

public class CustomHttpClient {
    /** The time it takes for our client to timeout */
    public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds

    /** Single instance of our HttpClient */
    private static HttpClient mHttpClient;

    /**
     * Get our single instance of our HttpClient object.
     *
     * @return an HttpClient object with connection parameters set
     */
    private static HttpClient getHttpClient() {
        if (mHttpClient == null) {
            mHttpClient = new DefaultHttpClient();
            final HttpParams params = mHttpClient.getParams();
            HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
            HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
            ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
        }
        return mHttpClient;
    }

    /**
     * Performs an HTTP Post request to the specified url with the
     * specified parameters.
     *
     * @param url The web address to post the request to
     * @param postParameters The parameters to send via the request
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpPost request = new HttpPost(url);
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
            request.setEntity(formEntity);
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Performs an HTTP GET request to the specified url.
     *
     * @param url The web address to post the request to
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpGet(String url) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(url));
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
于 2012-11-06T09:29:15.520 回答
0

您的 android 客户端必须对您的 PHP 脚本执行 Http 发布,该脚本返回状态代码。您的脚本将该请求视为任何其他发布请求。客户端从服务器接收结果,并进行所需的计算。

于 2012-11-06T06:52:01.637 回答
0

只需遵循此代码,我认为它的工作正常...

$email = isset($_REQUEST['email'])?urldecode($_REQUEST['email']):"";
$passwd= isset($_REQUEST['passwd'])?urldecode($_REQUEST['passwd']):"";
if($email==""||$passwd=="" )
{
$return_data['status'] = 0;

}
else
{
  $user_info="select id from table name WHERE email=$emailAND passwd=$passwd";
    if($user_info)
      {
       $return_data['status'] = 1;
      }
     else
    {
     $return_data['status'] = 0;
    }
}
echo json_encode($return_data);
于 2012-11-06T07:00:18.320 回答