Skip to content
Advertisement

Error in sending and recieving json object from Android to php using JsonObjectRequest method

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?

Advertisement

Answer

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 ”

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement