簡體   English   中英

java.lang.String 類型的值無法轉換為 JSONObject (Volley Android Php API)

[英]Value of type java.lang.String cannot be converted to JSONObject ( Volley Android Php API)

您好,我在使用 php 編寫 REST Api 的 volley api 中遇到問題,當我使用另一個 rest 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);

                }

我的 android volley 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);


[英]Value <br of type java.lang.String cannot be converted to JSONObject

暫無
暫無

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

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