簡體   English   中英

Android HTTPPOST執行兩次PHP腳本

[英]Android HTTPPOST executing PHP script twice

我正在開發一個基本的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對我來說是新手,所以這是實現此目的的錯誤途徑嗎?

謝謝

您兩次調用“ httpclient.execute(..)”:

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

刪除其中之一應該可以解決您的問題:)

您不需要將AsynTask子類(RegisterUser)調用到線程中,因為它是一個線程itelt,它耗盡了主要的IU線程。 只需調用execute方法。

而不是做:

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

做:

                new RegisterUser().execute("");

可能可以解決問題。

此外,您將從DefaultHttpClient對象的第一行和第三行調用兩次execute方法:

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

它不是一個真正的答案,但是我將代碼轉換為使用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才能將響應代碼更改為數組。

同樣,這不能解決我的原始問題,但是是一種可行的替代方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM