gpt4 book ai didi

php - 从 php 脚本调用中获取响应

转载 作者:行者123 更新时间:2023-11-29 19:50:48 25 4
gpt4 key购买 nike

我有一个应用程序通过 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;
}

安卓代码

 //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();
}
}


});

}

希望我能得到帮助。

最佳答案

您可以尝试修改您的 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) );
}
}

关于php - 从 php 脚本调用中获取响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37173354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com