我有 2 个 java 脚本应该转到位于 http://localhost/phptesting/Register.php 上的 php 文件.我的脚本的 URL 链接它,但是当我发送注册请求时,没有任何反应。日志中什么也没有发生。
这是我的注册请求:
public class RegisterRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://localhost/phptesting/Register.php";
private Map<String, String> params;
public RegisterRequest(String username, String password,String isAdmin, Response.Listener<String> listener){
super(Method.POST, REGISTER_REQUEST_URL,listener,null);
params = new HashMap<>();
params.put("username",username);
params.put("password",password);
params.put("isAdmin",isAdmin+"");
}
public Map<String, String> getparams() {
return params;
}
}
这是我的注册 Activity 脚本:
createuser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String username = username1.getText().toString();
final String password = password1.getText().toString();
final String isadmin = isAdmin.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success){
Intent intent = new Intent(CreateUser.this, MainActivity.class);
CreateUser.this.startActivity(intent);
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(CreateUser.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry",null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(username,password,isadmin,responseListener);
RequestQueue queue = Volley.newRequestQueue(CreateUser.this);
queue.add(registerRequest);
}
});
我的 php 脚本是这样的;
<?php
$db_host = 'localhost:3306';
$db_user = 'root';
$db_pass = '';
$db_name = 'test';
$con = mysqli_connect($db_host,'user',$db_pass,$db_name);
if($con){
echo "connection successful";
}else{
echo "connection failed";
}
$age = $_POST["isAdmin"];
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO user (username,password,isAdmin) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($statement, "siss",$username,$password,$isAdmin);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
感谢所有帮助。
最佳答案
我看到这段代码至少有两个错误:
private static final String REGISTER_REQUEST_URL = "http://localhost/phptesting/Register.php";
Android 不喜欢 localhost
你可以阅读它 here .
最好的选择是执行 ifconfig
并获取您的 ip 地址
而不是 localhost
放置您的 ip 地址
喜欢
你的本地主机也应该有一个端口,对吧?因此,请确保将其添加到 BASE_URL
中以防万一,因此它应该看起来像这样
然后调用应该工作。
然后我看到另一个问题
mysqli_stmt_bind_param($statement, "siss",$username,$password,$isAdmin);
您将 4 个值传递给需要 3 个值的插入。
我建议你一步一步来,首先确保你的 api 调用正在注册一些东西(你可以使用 PostMan 或 ARC 来完成)然后转到 Android 端。
关于java - Android Studio 没有与我的 PHP 脚本通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53119208/