Android登录认证到远程MySQL数据库

时间:2011-11-26 12:47:41

标签: java android

这是我的java代码:

btnLogin.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
    ArrayList < NameValuePair > postParameters = new ArrayList < NameValuePair > ();
    postParameters.add(new BasicNameValuePair("username", txtUsername.getText().toString()));
    postParameters.add(new BasicNameValuePair("password", txtPassword.getText().toString()));

    //String valid = "1";  
    String response = null;
    try {
      response = CustomHttpClient.executeHttpPost("http://www.sampleweb.com/imba.php", postParameters);
      String res = response.toString();
      // res = res.trim();  
      res = res.replaceAll("\\s+", "");
      //error.setText(res);  
      if (res.equals("1")) {
        txtError.setText("Correct Username or Password");
        //Intent i = new Intent(CDroidMonitoringActivity.this, MenuClass.class);
        //startActivity(i);
      } else {
        txtError.setText("Sorry!! Incorrect Username or Password");
      }
    } catch (Exception e) {
      txtUsername.setText(e.toString());
    }
  }
});

我认为我的res.equals有一个错误,因为即使我输入了正确的用户名或密码,它仍然会说“无效的用户名或密码”。但是,当我将res.equals更改为res.contains时,即使我输入了正确的用户名和密码,它仍然会说“正确的用户名或密码”。我真的需要你的帮助。所有掌握在android开发中的人。希望你能帮助我。而且,当我更改txtError.setText(res)以检查它是否返回1和0时它不会。

2 个答案:

答案 0 :(得分:1)

这需要在不在Android代码中的php文件中完成:

<?php

define('DB_USER', "root"); //username used to connect to the database.
define('DB_PASSWORD', ""); //password used to connect to the database.
define('DB_DATABASE', "dbname"); //database name
define('DB_SERVER', "127.0.0.1"); //database server address

?>

使用JSON解析器,您需要解析服务器上的数据。您需要使用类似于以下内容的内容:

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    public JSONParser() {

    }

    //Method to connect to the database
    public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {

        //The following works just as in normal GET and POST methods
        try {
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

在第二个类中,您需要按如下方式定义连接参数:

public class UserFunctions {

    private JSONParser jsonParser;

    private static String loginURL = "http://www.sampleweb.com/login.php";
    private static String registerURL = "http://www.sampleweb.com/register.php";

    private static String login_tag = "login";
    private static String register_tag = "register";

    // constructor
    public UserFunctions(){
        jsonParser = new JSONParser();
    }

    /**
     * function make Login Request
     * @param email
     * @param password
     * */
    public JSONObject loginUser(String email, String password){
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("tag", login_tag));
        params.add(new BasicNameValuePair("email", email));
        params.add(new BasicNameValuePair("password", password));
        JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
        // return json
        // Log.e("JSON", json.toString());
        return json;
    }

    /**
     * function make Login Request
     * @param name
     * @param email
     * @param password
     * */
    public JSONObject registerUser(String name, String email, String password){
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("tag", register_tag));
        params.add(new BasicNameValuePair("name", name));
        params.add(new BasicNameValuePair("email", email));
        params.add(new BasicNameValuePair("password", password));

        // getting JSON Object
        JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
        // return json
        return json;
    }

    /**
     * Function get Login status
     * */
    public boolean isUserLoggedIn(Context context){
        DatabaseHandler db = new DatabaseHandler(context);
        int count = db.getRowCount();
        if(count > 0){
            // user logged in
            return true;
        }
        return false;
    }

    /**
     * Function to logout user
     * Reset Database
     * */
    public boolean logoutUser(Context context){
        DatabaseHandler db = new DatabaseHandler(context);
        db.resetTables();
        return true;
    }

}

除此之外,您最终还是需要使用应用程序类来解析数据并将其显示给用户。有几个关于如何做到这一点的在线教程。

希望这会有所帮助:)

答案 1 :(得分:1)

很难弄清楚服务器的响应是怎么回事。要调试此问题,对于有效和无效的用户名/密码组合,请使用POST http://www.sampleweb.com/imba.phpcurl

检查Postman的响应