【问题标题】:Android HTTPPOST executing PHP script twiceAndroid HTTPPOST 执行 PHP 脚本两次
【发布时间】:2015-02-05 04:52:58
【问题描述】:

我正在开发一个基本的 Android APK,它将成为我运行的网站的基本移动版本。 APK 的一部分使人们能够注册用户帐户(基本注册)。我正在使用 HTTPPOST 将用户表单信息发送到 PHP 脚本。我所有的错误检查都有效(密码匹配、长度等),但我从有效提交中得到的响应,我可以告诉它试图运行 PHP 两次。 APK 将收到一条错误消息并告诉用户用户名和密码已被使用,但这是因为 php 运行时插入数据,然后由于某种原因再次运行并报告错误捕获而不是仅仅第一次运行时报告成功。如果我取出错误捕获来查找重复的用户名和电子邮件,我可以在我的数据库中看到两个插入。为什么 PHP 页面会运行两次?

步骤:

  1. 清除用户数据库。
  2. 插入有效的注册信息(以免引发错误)。

结果

APK 显示错误消息,说明用户名和密码已被使用。 SQL 数据库显示表单中的信息已插入。

文件

我将日志记录在我的 APK 中,它似乎只调用一次 HTTPPOST。下面是 JAVA 文件和 PHP 页面。对此的任何煽动将不胜感激。

JAVA 文件

Register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("Registration: ", "Button Pressed");
            dialog = ProgressDialog.show(Register.this, "",
                    "Creating account...", true);
            new Thread(new Runnable() {
                public void run() {
                    new RegisterUser().execute("");
                }
            }).start();
        }
    });
}

private class RegisterUser extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... arg0) {
        try {


            httpclient = new DefaultHttpClient();
            // This is the page that will get all the information to create the account
            HTTPPOST = new HttpPost("http://www.linetomyphppage.php");

            NAMEVALUEPAIRS = new ArrayList<NameValuePair>();

            NAMEVALUEPAIRS.add(new BasicNameValuePair("username",username.getText().toString().trim()));  // $Edittext_value = $_POST['Edittext_value'];
            NAMEVALUEPAIRS.add(new BasicNameValuePair("userEmail",emailaddress.getText().toString().trim()));
            NAMEVALUEPAIRS.add(new BasicNameValuePair("password1",password1.getText().toString().trim()));
            NAMEVALUEPAIRS.add(new BasicNameValuePair("password2",password2.getText().toString().trim()));
            NAMEVALUEPAIRS.add(new BasicNameValuePair("newsletter",subscribe));

            HTTPPOST.setEntity(new UrlEncodedFormEntity(NAMEVALUEPAIRS));
            HTTPRESPONSE = httpclient.execute(HTTPPOST);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            final String response = httpclient.execute(HTTPPOST, responseHandler);
            Log.d("Registration: ", "Executing Post");
            errorcode = response;

            // Redirect the user depending on the response
            if (response.equalsIgnoreCase("success")) {
               // Toast.makeText(Register.this, "Registration successful", Toast.LENGTH_SHORT).show();
                Log.d("Registration: ", "Registration successful");
                valid = "Successful";
            } else {
                Log.d("Registration: ", "Registration failed");
                valid = "Invalid";
              //  Toast.makeText(Register.this, "Registration failed: " + response, Toast.LENGTH_SHORT).show();
            }


        } catch (Exception e) {
            System.out.println("Exception here : " + e);
        }
        dialog.dismiss();
        return "Executed";
    }
    @Override
    protected void onPostExecute(String result){

        if(valid.equalsIgnoreCase("Invalid")){
            Log.d("Registration: ", "Error generated");
            String code = errorcode.replace("Invalid","");
            Toast.makeText(Register.this, "Registration failed: " + code, Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(Register.this, "Registration successful", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(Register.this, HomeScreen.class));
            finish();
        }
    }
}

PHP端

<?php 
// Connecting to database
$connect = $_SERVER['DOCUMENT_ROOT'];
$connect .= "pathtoconnect.php";
include_once($connect);

// Get all the variables being passed from the APK
$username = mysql_real_escape_string($_POST['username']);
$password1 = mysql_real_escape_string($_POST['password1']);
$password2 = mysql_real_escape_string($_POST['password2']);
$email = mysql_real_escape_string($_POST['userEmail']);
$newsletter = mysql_real_escape_string($_POST['newsletter']);
$pass = 1;
$error = false;

// Check if the username is valid. 
if (preg_match('/[^0-9a-z-_]/i', $username) == 1) {
    $error = 'You can not use spaces or strange characters in a usermame.';
    $pass = 0;      
}
if(strlen($username) < 5) { // Ensure the length is at least 5
    $error = 'Username must be at least 5 characters.';
    $pass= 0 ;
}
if(strlen($password1) < 5) { // Ensure the length is at least 5
    $error = 'Passwords have to be at least slightly challenging (5+ characters).';
    $pass= 0 ;
}

if($password1 != $password2) { // Check for passwords to match
    $error = "Your passwords did not match. Please try again.";
    $pass= 0 ;  
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { // Check to make sure email address is valid
    $error = "The email address you entered is not valid. Double check it.";
    $pass= 0 ;
}

// check if username or email is already in use
$checking = mysql_query("SELECT COUNT(user_id) AS total FROM users WHERE username='$username' OR email='$email'");
$checking = mysql_fetch_array($checking);
if($checking['total'] > 0) {
    $error = 'The username or email you are trying to use is already in use. Please go to the website if you forgot your password to reset it.';    
    $pass= 0 ;
}
if(!$error) {
    echo 'success';
    $time = time();
    mysql_query("INSERT INTO users (username, password, email, date_created, subscription) VALUES ('$username', md5('$password1'), '$email',  '$time', '$subscribe')"); 


    }
else {
    echo 'Invalid'.$error;  
}

?>

设备正在报告重复错误,正如我所提到的,数据被插入,因此“成功”之类的不会得到回显。 下面是来自 JAVA 文件的日志,显示它只收到失败的响应。

02-04 22:31:37.442  26159-26159/com.demo D/Registration:﹕ Button Pressed
02-04 22:31:37.862  26159-26559/com.demo D/Registration:﹕ Executing Post
02-04 22:31:37.862  26159-26559/com.demo D/Registration:﹕ Registration failed
02-04 22:31:37.872  26159-26159/com.demo D/Registration:﹕ Error generated

我构建了一个基本的 html 表单来传递数据,并且该方法运行良好,执行 php 一次,所以我不知所措。 Android/JAVA 对我来说是新的,所以这是实现这一目标的错误途径吗?

谢谢

【问题讨论】:

    标签: java php android http-post


    【解决方案1】:

    您正在调用“httpclient.execute(..)”两次:

    HTTPRESPONSE = httpclient.execute(HTTPPOST);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    final String response = httpclient.execute(HTTPPOST, responseHandler);
    

    删除其中一个应该可以解决您的问题:)

    【讨论】:

      【解决方案2】:

      您不需要将您的 AsynTask 子类 (RegisterUser) 调用到 Thread 中,因为它是一个 Thread itselt,它会在主 IU Thread 之外运行。只需调用 execute 方法即可。

      而不是做:

      new Thread(new Runnable() {
                  public void run() {
                      new RegisterUser().execute("");
                  }
              }).start();
      

      做:

                      new RegisterUser().execute("");
      

      也许它可以解决问题。

      另外,您从 DefaultHttpClient 对象调用了两次执行方法,第一行和第三行:

      HTTPRESPONSE = httpclient.execute(HTTPPOST);
      ResponseHandler<String> responseHandler = new BasicResponseHandler();
      final String response = httpclient.execute(HTTPPOST, responseHandler);
      

      【讨论】:

      • 感谢您的回复,但不幸的是我得到了相同的结果;新帐户被创建,然后 php 再次运行并返回重复帐户错误。
      • 我刚刚在我的基本登录页面(有效)上添加了一个虚拟 INSERT 命令进行了测试。果然,该脚本也运行了两次。那么为什么我的 httppost 会两次运行 php 页面呢?
      【解决方案3】:

      这不是一个真正的答案,但我将代码转换为使用 JSON 请求而不是 httppost 方法,并且效果更好。

      Log.d("JSON", "Running the JSON script");
                  JSONObject json = jsonParser.makeHttpRequest(url_register, "POST", params);
      
                  //Getting specific Response
                  try {
                      RESPONSE_STATUS = json.getInt("success");
                      RESPONSE_MESSAGE = json.getString("message");
      
                  } catch (JSONException e) {
                      RESPONSE_MESSAGE = "An error has occured during the registration";
                      e.printStackTrace();
                  }
                  Log.d("JSON", json.toString());
                  Log.d("Registration: ", "Response Status: " + RESPONSE_STATUS);
                  Log.d("Registration: ", "Response: " + RESPONSE_MESSAGE);
      
                  // Redirect the user depending on the response
                  if (RESPONSE_STATUS == 1) {
                      Log.d("Registration: ", "Registration successful");
                      valid = "Successful";
                  } else {
                      Log.d("Registration: ", "Registration failed");
                      valid = "Invalid";
                  }
      

      这确实需要完全重写 php 以将响应代码更改为数组。

      同样,这并不能解决我原来的问题,而是一种可行的替代方法。

      【讨论】:

        猜你喜欢
        • 2013-02-04
        • 2012-03-06
        • 2013-11-14
        • 1970-01-01
        • 2012-08-01
        • 2011-10-19
        • 2020-07-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多