java.lang.String 类型的值无法转换为 JSONObject(Volley Android Php API



你好,我在 volley api 调用用 php 编写的 REST API 时遇到问题,当我使用另一个 rest api 它有效时,但当我使用我的 API 时它不起作用,所以我认为问题出在我的 php api 中,但我找不到它。 这是我的 php db 连接:

<?php
$dsn = 'mysql:dbname=android;host=localhost';
$user = 'root';
$password = '';
try {
$db = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connexion échouée : ' . $e->getMessage();
}

我的all_clients.php

if ($_SERVER['REQUEST_METHOD'] == "POST") {
if ($_GET['url'] == "auth")   {
$username = $_POST["username"];
$password = $_POST["password"];
$stmt=$db->prepare("SELECT * FROM users WHERE username=? and password=?");
$stmt->execute([$username,$password]); 
if ($row=$stmt->fetch()) {              
$response["message"]="valid";       
} else {
$response["message"]="invalid";
} 
echo json_encode($response);
}

我的安卓凌空 API 代码:

RequestQueue rq = Volley.newRequestQueue(this);
String url = "http://192.168.11.100/webservice/all_clients.php?url=auth";
StringRequest sr = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
JSONObject json= null;;
Log.d("ffhnf", response);
User user = null;
try {
json = new JSONObject(response);

} catch (JSONException e) {
e.printStackTrace();
}

我得到的错误:java.lang.String类型的值无法转换为JSONObject

尝试使用JsonObjectRequest

JSONObject obj = new JSONObject();
obj.put("username", username);
obj.put("password", password);
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.POST, url, obj,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// Here is your json
json = response
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Handle Error;
}
});
rq.add(jor);

最新更新