【问题标题】:Value of type java.lang.String cannot be converted to JSONObject ( Volley Android Php API)java.lang.String 类型的值无法转换为 JSONObject(Volley Android Php API)
【发布时间】:2019-12-05 19:21:54
【问题描述】:

您好,我在 volley api 中调用 REST Api 用 php 编写时遇到问题,当我使用另一个 rest api 时它可以工作,但是当我使用我的时它没有,所以我认为问题出在我的 php api 但我找不到。 这是我的 php 数据库连接:

<?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

【问题讨论】:

  • 如果您直接从 Postman 或 cURL 等访问 API 会发生什么?
  • 它给了我一个像这样的 json 对象 { "message": "valid" }
  • 所以如果你从另一个应用程序(邮递员、curl 等)调用 API,你会得到预期的结果吗?然后它听起来并不是真正的问题是API。顺便说一句,您真的不应该以纯文本形式存储密码。您应该使用password_hash() 对密码进行哈希处理,并且只将哈希值存储在数据库中。
  • 是的,谢谢,这只是为了测试目的,我稍后会更改

标签: java php android


【解决方案1】:

尝试使用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);

【讨论】:

  • 你好,谢谢你的回复我已经试过了,我得到了这个错误:org.json.JSONException: Value
猜你喜欢
  • 1970-01-01
  • 2023-03-10
  • 2021-10-23
  • 2017-11-23
  • 1970-01-01
  • 1970-01-01
  • 2017-02-03
  • 2017-10-02
  • 2013-08-02
相关资源
最近更新 更多