从php脚本调用获得响应

时间:2016-05-11 21:10:38

标签: php android json rest

我有一个应用程序通过POST将一些信息发送到服务器中的php脚本。它使用Asynchttpclient。我怎样才能收到服务器的回复(通过json?)?请帮忙。

这是我的php脚本

if($_POST["mode"]=="newuser"){
            //$gcmRegID  = $_GET["shareRegId"]; 
            $gcmRegID  = $_POST["regID"]; 
            $gcmUserName  = $_POST["userName"]; 
            $gcmFolderName = $_POST["folderName"];

            $gcmDate = date("d/m/y");

            $conn = new mysqli($servername, $username, $password, $dbname);
            if($conn->connect_error){
                die("Connection failed: " . $conn->connect_error);
            }
            $in_user = "user";
            $in_password = "NULL";
            $in_email = "NULL";
            $in_dob = "NULL";
            $in_role = "user";
            $in_datejoined = "0000-00-00";
            $foldername = "NULL";

            $sql = "INSERT INTO user(password,regid,name,email,phone,dob,role,datejoined,foldername) VALUES('$in_password','$gcmRegID','$gcmUserName','$in_email','$in_phone','$in_dob','$in_role','$gcmDate','$foldername')";

            $substringtitle = substr($gcmRegID,-7);
            $combined = $gcmUserName."_".$substringtitle;
            if($conn->query($sql)===TRUE){
                    mkdir("./users/".$gcmFolderName);
                    $newfoldername = "./users/".$gcmFolderName;
                    $updatequery = "UPDATE user SET foldername='$newfoldername' WHERE name='$gcmUserName'";


                     $returnfield = array(
                        'foldername' => $newfoldername
                    );
                    header('Content-type: application/json');
                    echo json_encode(array('returnfield'=>$returnfield));


                    if($conn->query($updatequery)===TRUE){
                        echo "folder updated";
                    }
                    //echo "Folder created!";
                //}
                echo "New record created successfully";

            }else{
                echo "Error: " . $sql . "<br>" . $conn->error;
            }
            $conn->close();

            echo "Done!";
            exit;
        }

Android代码

 //store in the file server (PHP)
private void storeREG(final String registerID,String userName,String folderName){

    pg.show();
    params.put("regID", registerID);
    params.put("userName",userName);
    params.put("folderName", folderName);
    params.put("mode","newuser");
    Log.d("STORE","STORE");
    //Make RESTful webservice call

    AsyncHttpClient client = new AsyncHttpClient();
    client.post(AppConstants.SERVER_URL, params, new AsyncHttpResponseHandler() {

        @Override
        public void onSuccess(String content) {
            pg.hide();
            if (pg != null) {
                pg.dismiss();
            }


            Toast.makeText(applicationCtx, "ID sharing successful", Toast.LENGTH_LONG).show();
            Intent home = new Intent(applicationCtx, HomeActivity.class);
            home.putExtra("regID", registerID);
            Log.d("REGID", registerID);
            startActivity(home);
            finish();
        }

        @Override
        public void onFailure(int statusCode, Throwable error, String content) {
            pg.hide();
            if (pg != null) {
                pg.dismiss();
            }
            Log.d("ERRORTHROW", error.toString());
            if (statusCode == 404) {
                Toast.makeText(applicationCtx, "Requested resource not found", Toast.LENGTH_LONG).show();
            } else if (statusCode == 500) {
                Toast.makeText(applicationCtx, "Something went wrong at the server", Toast.LENGTH_LONG).show();
            } else {
                Log.d("SHOWME", String.valueOf(statusCode));
                Toast.makeText(applicationCtx, "Unexpected error occurred", Toast.LENGTH_LONG).show();
            }
        }


    });

}

希望我能得到帮助。

2 个答案:

答案 0 :(得分:1)

我现在无法测试代码(抱歉),但我认为它应该是这样的:

try {
    RequestParams rParams = new RequestParams();
    rParams.put("example", "example"); // POST
    AsyncHttpClient client = new AsyncHttpClient();
    client.get(pageURL, rParams, new JsonHttpResponseHandler() {

        @Override
        public void onSuccess(JSONArray jsonArray) {
            super.onSuccess(jsonArray);

            //process JSON Array

        }

        @Override
        public void onFailure(Throwable throwable, JSONArray jsonArray) {
            super.onFailure(throwable, jsonArray);
            Log.d(TAG, "error", throwable);
        }

    });
} catch (Exception e) {
    Log.d(TAG, "exception", e);
}

否则我做了一个非常轻松的WebClient,你可能想试一试:

<强> https://github.com/omaflak/WebClient

这是一个简短的样本:

WebClient client = new WebClient();
client.setOnRequestListener(new OnRequestListener() {
        @Override
        public void onRequest(String response, int requestID) {
            Log.e(TAG, response);
        }

        @Override
        public void onError(int error_code, String message) {
            Log.e(TAG, message);
        }
});

Pair p = new Pair("field1", "value1");
Pair p2 = new Pair("field2", "value2");
client.requestAsync("http://your-api.com", WebClient.POST, Arrays.asList(p, p2), 1);

//  requestAsync(String url, String method, List<Pair<String, String>> postData, int requestID)

要使用它,只需添加到您的依赖项:

compile 'me.aflak.libraries:webclient:1.0'

答案 1 :(得分:1)

您可以尝试修改PHP代码。以下是一个经过充分评论的示例代码,可帮助您入门:

    <?php
        // EXPLICITLY INSTRUCT THE HEADER ABOUT THE CONTENT TYPE. HERE - JSON 
        header('Content-type: application/json');

        if($_POST["mode"]=="newuser"){
            $gcmRegID       = htmlspecialchars(trim($_POST["regID"]));
            $gcmUserName    = htmlspecialchars(trim($_POST["userName"]));
            $gcmFolderName  = htmlspecialchars(trim($_POST["folderName"]));
            $gcmDate        = date("d/m/y");

            // I WOULD STRONGLY SUGGEST YOU USE PDO FOR YOUR DATABASE TRANSACTIONS:
            // HERE'S HOW:

            //DATABASE CONNECTION CONFIGURATION:
            defined("HOST")     or define("HOST",   "localhost");           //REPLACE WITH YOUR DB-HOST
            defined("DBASE")    or define("DBASE",  "database");            //REPLACE WITH YOUR DB NAME
            defined("USER")     or define("USER",   "root");                //REPLACE WITH YOUR DB-USER
            defined("PASS")     or define("PASS",   "root");                //REPLACE WITH YOUR DB-PASS

            // ESTABLISH A CONNECTION AND DO YOUR WORK WITHIN A TRY-CATCH BLOCK...
            try {
                $dbh        = new PDO('mysql:host='.HOST.';dbname='. DBASE,USER,PASS);
                $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                // HERE: ALL YOUR BUSINESS LOGIC...
                $in_user        = "user";
                $in_password    = "NULL";
                $in_email       = "NULL";
                $in_phone       = "NULL";
                $in_dob         = "NULL";
                $in_role        = "user";
                $in_dateJoined  = "0000-00-00";
                $folderName     = "NULL";

                $insertSQL      = "INSERT INTO user(`password`, `regid`, `name`, `email`, `phone`, `dob`, `role`, `datejoined`, `foldername`) ";
                $insertSQL     .= " VALUES(:inPassword, :gcmRegID, :gcmUserName, :inEmail, :inPhone, :inDOB, :inRole, :gcmDate, :folderName)";

                $arrInsertData  = array(
                    'inPassword'    => $in_password,
                    'gcmRegID'      => $gcmRegID,
                    'gcmUserName'   => $gcmUserName,
                    'inEmail'       => $in_email,
                    'inPhone'       => $in_phone,
                    'inDOB'         => $in_dob,
                    'inRole'        => $in_role,
                    'gcmDate'       => $gcmDate,
                    'folderName'    => $folderName
                );

                // PREPARE THE INSERT QUERY:
                $insertStmt = $dbh->prepare($insertSQL);

                // INSERT THE NEW ROW:
                $insertStmt->execute($arrInsertData);

                // OBTAIN THE ID OF THE INSERTED ROW TO BE USED AS SUFFIX FOR YOUR USER FOLDER
                $id         = $dbh->lastInsertId();

                // WHAT HAPPENS WHEN 2 USERS HAVE THE SAME USERNAME??? DID YOU THINK ABOUT THAT?
                // TO CIRCUMVENT THIS ISSUE; I WOULD SUGGEST FIRST TO INSERT THE DATA TO THE DATABASE...
                // THEN USE THE ID AS A SUFFIX TO MAKE EACH USER DIRECTORY UNIQUE & THAT IS THE APPROACH TAKEN HERE THOUGH...

                // NOW YOU CAN CREATE YOUR FOLDER USING THIS ID: $id
                // LIKE THIS; 2 USERS WITH USERNAME "android_user" CAN HAVE 2 DIFFERENT FOLDERS LIKE SO: "android_user_97" & "android_user_102"
                $userDirectory  = "./users/" . $gcmFolderName . "_" . $id;
                mkdir($userDirectory);

                // DID IT OCCUR TO YOU THAT 2 USERS MIGHT HAVE THE SAME USERNAME IN WHICH CASE MYSQL (INSTEAD OF YOU) HAS TO DECIDE WHICH USER TO UPDATE?
                // THAT IS WHY DATABASE TABLES ARE DESIGNED TO HAVE UNIQUE IDENTIFIERS LIKE UUID OR ID OR UID OR ANY TOKEN TO MAKE EACH ROW UNIQUE...
                // WE ARE ADOPTING THIS APPROACH IN THE UPDATE QUERY... THAT IS: WE UPDATE THE ROW USING THE ID ABOVE... ASSUMING THAT IS A UNIQUE COLUMN THOUGH.
                $updateSQL      = "UPDATE user SET foldername=:newDirName WHERE id=:ID";

                // NOW UPDATE THE ROW TO TAKE INTO ACCOUNT THE UNIQUE USER-DIRECTORY (USING THE ID AS THE KEY)
                $arrUpdateData  = array(
                    'newDirName'    => $userDirectory,
                    'ID'            => $id      // THIS ASSUMES THAT THE PRIMARY KEY OF YOUR TABLE IS CALLED id OTHERWISE USE THE APPROPRIATE KEY NAME: EG: reg_id OR WHATEVER
                );

                // PREPARE THE UPDATE QUERY:
                $insertStmt = $dbh->prepare($updateSQL);

                // UPDATE THE NEWLY CREATED ROW:
                $insertStmt->execute($arrUpdateData);

                // BUILD THE RESPONSE JSON DATA
                $arrResponse    = array(
                    'folderName'    => $userDirectory,
                    'id'            => $id,
                );

                // SEND THE RESPONSE AS JSON IF ALL WORKS FINE TILL HERE... 
                // THAT MEANS: SEND THE DATA IN $arrResponse AND TERMINATE THE SCRIPT - THE JOB IS DONE.
                // NO NEED FOR ALL THOSE ECHO STATEMENTS AS THE YOU ARE EXPLICITLY SENDING BACK JSON DATA.
                die( json_encode($arrResponse) );

            }catch(PDOException $e){
                // IF THERE WAS ANY KIND OF PDO ERROR, SEND IT BACK ANYWAYS - BUT ALSO AS JSON:             
                $arrResponse    = array(
                    'error'     => $e->getMessage()
                );
                die( json_encode($arrResponse) );
            }
        }