代码之家  ›  专栏  ›  技术社区  ›  Pushan Gupta

凌空抽射没有反应

  •  1
  • Pushan Gupta  · 技术社区  · 8 年前

    这似乎是一个已经问过的问题,但我已经尝试了stackoverflow上的几乎所有问题。

    com.android.volley.ParseError: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
    

    因此参数必须看起来像:

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
           Map<String, String> params = new HashMap<String, String>();
           params.put(KEY_USERNAME, "loyal_customer");
           params.put(KEY_PASSWORD, "custumerXYZ");
           params.put(KEY_INFO, "merchant_names");
    
           return params;
    }
    

    其中,全局中的键定义为:

      public static final String KEY_USERNAME="username";
        public static final String KEY_PASSWORD="password";
        public static final String client_side_php="https://vidorvistrom.000webhostapp.com/client_access.php";
        public static final String KEY_INFO="info_req";
    

    这是我在onClick()监听器中调用的makeRequest()方法:

    public void makeRequest() {
            RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
            final JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, client_side_php, null,
                    new Response.Listener<JSONObject>() {
    
                        @Override
                        public void onResponse(JSONObject response) {
    
                            try {
                                Log.d("response: ", String.valueOf(response.getJSONObject("name")));// response.getString("name") also tried and name is the column name in the database which works fine with GET
    
                            } catch (JSONException e) {
                                Log.d("this: ",e.toString());
                                e.printStackTrace();
                            }
    
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
    
                        }
                    }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> params = new HashMap<String, String>();
                    params.put(KEY_USERNAME, "loyal_customer");
                    params.put(KEY_PASSWORD, "custumerXYZ");
                    params.put(KEY_INFO, "merchant_names");
    
                    return params;
                }
    
            };
            requestQueue.add(jsObjRequest);
        }
    

    恐怕我错过了什么。这是我第一次尝试凌空抽射。

    应用程序不会崩溃。它什么都不做。

    <?php
    
    $username=$_POST["username"];
    $password=$_POST["password"];
    $info_req=$_POST["info_req"];
    
    if($info_req==""){
      $string.="Error 404. Not Found";
      $data[]=$string;
    }
    else{
    
    $con=mysqli_connect(details hidden from public);
    
    $string="";
    $data=array();
    
    if(!$con){
       $string.="Connection Failed. Bad Access to database!";
       $data[]=$string;
    
    }
    else{
    
    
        $query="Select * from client_side_records where username='{$username}'";
    
        $result=mysqli_query($con,$query);
    
        $row=mysqli_fetch_assoc($result);
    
        $pass_db=$row["password"];
    
    
       if($pass_db==$password){
            if($info_req=="merchant_names"){
                $query="Select name, id from merchant_side_records";
                $result=mysqli_query($con,$query);
                while($row=mysqli_fetch_assoc($result)){
                    foreach($row as $key => $value) {
                        $data[$key] = $value;
                    }
                }
    
    
             }
    
       }
       else{
         $string.="Login Failed";
         $data[]=$string;
       }
    }
    
    }
        $data=json_encode($data);  
        echo $data;
    
    ?>
    

    正如我建议的那样,我试着使用Hull。为了检查服务器是否响应post请求,我似乎很好:

    POST https://vidorvistrom.000webhostapp.com/client_access.php
    
     200 OK       36 bytes       480 ms
    
    View Request View Response
    HEADERS
    
    Connection: keep-alive
    Content-Encoding: gzip
    Content-Type: text/html; charset=UTF-8
    Date: Tue, 25 Jul 2017 12:09:17 GMT
    Server: awex
    Transfer-Encoding: chunked
    X-Content-Type-Options: nosniff
    X-Request-Id: 8edf2f8e9e53f138e700aef92d58045a
    X-Xss-Protection: 1; mode=block
    BODY view formatted
    
    {"name":"Paan Singh Tomar","id":"1"}
    
    3 回复  |  直到 8 年前
        1
  •  1
  •   Athar Iqbal    8 年前
    <?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
      require_once("dbcon.php");
      $response=array();
      $response['error'] = false;
      $response['merchants'] = array();
      if (isset($_POST['username']) && isset($_POST['password']) && isset($_POST['info_req'])) {
        $username = $_POST['username'];
        $password = $_POST['password'];
        $info_req = $_POST['info_req'];
        $con=mysqli_connect(details hidden from public);
        if (!$con) {
          $response['error'] = true;
          $response['message'] = "Connection Failed. Bad Access to database!";
        } else {
          $query="SELECT * FROM client_side_records WHERE username = '{$username}'";
          $result=mysqli_query($con,$query);
          $row =mysqli_fetch_assoc($result);
          $pass_db = $row["password"];
            if($pass_db==$password){
              if($info_req == "merchant_names"){
                $query="SELECT name, id FROM merchant_side_records";
                $result=mysqli_query($con,$query);
                while($row=mysqli_fetch_assoc($result)){
                  $temp = array();
                  $temp['id'] = $row['id'];
                  $temp['name'] = $row['name'];
                  array_push($response['merchants'], $temp);
                }
              } else if($info_req == "merchant_details") {
                 $merchant_id = $_POST["merchant_id"];
                 $query="SELECT name, shop_name, address FROM merchant_side_records WHERE id='{$merchant_id}'";
                 $result=mysqli_query($con,$query);
                 while($row=mysqli_fetch_assoc($result)) {
                  $temp = array();
                  $temp['name'] = $row['name'];
                  $temp['shop_name'] = $row['shop_name'];
                  $temp['address'] = $row['address'];
                  array_push($response['merchants'], $temp);
                }
            }
          } else {
            $response['error'] = true;
            $response['message'] = "Login failed";
          }
        }
      } else {
        $response['error'] = true;
        $response['message'] = "404 not found...";
      }
    } else {
      $response['error'] = true;
      $response['message'] = "Please check method. it must be POST";
    }
    header("content-type:application/json");
    echo json_encode($response);
    ?>
    
    //output as shown below as jsonarray
    {
    "error": false
    "merchants": [{
    "id": 1,
    "name": abc
    },
    {
    "id": 1,
    "name": xyz
    }]
    }
    
    // change ur android response in volley
    boolean error = response.getBoolean("error"));
    if(!error) {
    JsonArray jsonArray = response.getJSONArray("merchants"));
    for(int i = 0; i < jsonArray.length(); i++) {
    JSONObject jsonObject = jsonArray.getJSONObject(i);
    String name = jsonObject.getString("name");
    }
    }
    
        2
  •  1
  •   Pushan Gupta    8 年前

    好的,我已经研究了相当多的主题一段时间,以找到解决这个问题的方法。

    精确问题

    我在过去几年里读到的许多答案大多都是这样的:

    • 生成StringRequest,而不是JSONObject Request或JsonArrayRequest
    • 数据库中存储的值中存在一些错误
    • 解析json时出错

    但在此之前,让我概述一下我最初在做什么

    • 发出JSONObject请求
    • getBody() getParams() 方法中创建哈希映射。
    • 使用$\u POST[”在php中检索POST参数 "]
    • 从中的数据库检索信息 无论如何 然后将它们编码为json并响应它们。

    在继续之前,我想明确一件事:

    • 两者之间存在差异 JSON数组

    this 如果你在继续之前还不知道。

    • 典型的StringRequest如下所示

      StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
              @Override
              public void onResponse(String response) {
                  .
                  .
                  .
      
              }
          }, new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                  .
                  .
                  .
              }
          }){
                                  .
                  .
                  .
      
          };
          RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
          requestQueue.add(stringRequest);
      

    您可以收集该字符串并从中生成JSON对象。字符串必须看起来像 this .

    然后以正常方式继续(操作JSON对象…)

    • 其次,传递POST参数不会以通常的覆盖方式工作。你必须制作一个地图并向其添加参数。然后从中生成一个JSON对象,并在第三个参数中传递该对象。

    类似于:

    Map<String, String> **params** = new HashMap<String, String>();
            params.put(KEY_USERNAME, "loyal_customer");
            params.put(KEY_PASSWORD, "custumerXYZ");
            params.put(KEY_INFO, "merchant_names");
            JSONObject parameters =new JSONObject(params);
    
     public JsonArrayRequest(int method, String url, JSONObject **params**,
        Listener<JSONArray> listener, ErrorListener errorListener)
    

    因此,您必须像这样解码这些post参数:

    $json = json_decode( file_get_contents('php://input') );
    

    if (isset($json->{'username'}) && isset($json->{'password'}) && isset($json->{'password'})) {
        $username = $json->{'username'};
        $password = $json->{'password'};
        $info_req = $json->{'info_req'};
    }
    

    然后,当您在onRespose内接收到JSON数组时,遍历它并操作其内容。

    • 如果使用JsonObjectRequest

      (不知为什么,至少在我的情况下,这更有趣!)

      同样,我们期望的是一个对象,而不是数组!

      以类似的方式,我们通过由映射组成的JSON对象发送参数,就像在JsonArrayRequest中一样

      因此,这必然意味着php正在接收JSON对象作为POST参数,我们必须在php内部执行与之前相同的操作(JsonArrayRequest)。

    在所有这些之后,还有一件重要的事情需要注意:

    • In my case(the working one) I went with the third way, receiving JSON object that contains a JSON array with all the necessary values in form of nested JSON objects. 
      

    类似这样:

    {"Tag":[{"error":true},{"id":1,"name":"Vidor Vistrom"},{"id":2,"name":"Dealo Ell"}]}
    

    您可能想看看我的实现(虽然php有安全漏洞!但供公众使用,所以不要怀疑公开披露):

        3
  •  0
  •   Anil    8 年前

    尝试覆盖 getBodyContentType

    @Override
    public String getBodyContentType() {
    return "application/x-www-form-urlencoded; charset=UTF-8";
                            }
    
    推荐文章