douyao3895 2019-07-07 21:15
浏览 225
已采纳

使用JsonObjectRequest方法从Android发送和接收json对象时出错

I want to make a custom select query on a table stored in a remote database for an android app. The following is my php file that takes tablename, fields and condition from POST method and makes a select query. Then it returns a json object of the rows fetched.

<?php
require("config.php");
$tablename=$_POST['tablename'];
$condition=$_POST['condition'];
$data=json_decode($_POST['fields']);
$fields = implode(",",$data );
$sql="SELECT $fields FROM $tablename WHERE $condition";
if($res=mysqli_query($con,$sql))
{
while ( $row = $res->fetch_object()) { $myArray[ ] = $row; }
echo json_encode($myArray,  JSON_FORCE_OBJECT);
}
else echo json_encode($sql." ".mysqli_error($con));
mysqli_close($con);
?>

I am sending a json object request from my android app using POST method as follows:

// Parameter Values:
String tablename = "teachers";
JSONArray fields = new JSONArray().put("password");
String condition = "teacher_id like \'" + id + "\'";



    Map<String,String> params=new HashMap<>();
    params.put("tablename",tablename);
    params.put("fields",fields.toString());
    params.put("condition",condition);
    JSONObject jsonRequest = new JSONObject(params);
    Toast.makeText(context, jsonRequest.toString(), Toast.LENGTH_SHORT).show();
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
                (Request.Method.POST, DOMAIN+"/select.php", jsonRequest, new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        Toast.makeText(context, "Success "+ response.toString(), Toast.LENGTH_LONG).show();
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // TODO: Handle error
                        Toast.makeText(context, "Error"+error.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });

     requestQueue.add(jsonObjectRequest);

The json object is formed correctly as seen here:

enter image description here

But I still get this error:

enter image description here

Can anyone help me get the json object of the output of the select query?

Update:

I updated both php and the java file to use POST instead of GET. Still the same error.

UPDATE:

I made this curl request that prints correct result

<?php
//The url you wish to send the POST request to
$url = "*****";

//The data you want to send via POST
$fields = [
    'tablename'      => 'teachers',
    'fields'        => '["password"]',
    'condition'    => 'teacher_id like \'MCA01\''
];

//url-ify the data for the POST
$fields_string = http_build_query($fields);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//So that curl_exec returns the contents of the cURL; rather than echoing it
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); 

//execute post
$result = curl_exec($ch);
echo $result;
?>

Output: {"0":{"password":"3438735f791**********************8e7e5d24a5"}}

Why is the request from android not working?

  • 写回答

1条回答 默认 最新

  • drlh197610 2019-07-07 21:22
    关注

    You cannot send JSON in a GET request.

    You should either not want to send any JSON:

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
                    (Request.Method.GET, DOMAIN+"/select.php", null, new Response.Listener<JSONObject>() {
    

    or do a POST

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
                    (Request.Method.POST, DOMAIN+"/select.php", jsonRequest, new Response.Listener<JSONObject>() {
    

    You can actually use a third constructor which lets the Volley library figure it out for itself:

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
                    (DOMAIN+"/select.php", jsonRequest, new Response.Listener<JSONObject>() {
    

    (and because your JSON is not null, it will use POST) See docs: https://afzaln.com/volley/com/android/volley/toolbox/JsonObjectRequest.html)


    with your edited question, I think the problem is now your server is sending back a response as HTML when the request is expecting the response to be JSON. I would either breakpoint to see what the full error is (that starts "

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站