Send post request using Volley and receive in PHP

Had a lot of problems myself, try this !

public class CustomRequest extends Request<JSONObject> {

private Listener<JSONObject> listener;
private Map<String, String> params;

public CustomRequest(String url,Map<String, String> params, Listener<JSONObject> responseListener, ErrorListener errorListener) {
    super(Method.GET, url, errorListener);
    this.listener = responseListener;
    this.params = params;
}

public CustomRequest(int method, String url,Map<String, String> params, Listener<JSONObject> reponseListener, ErrorListener errorListener) {
    super(method, url, errorListener);
    this.listener = reponseListener;
    this.params = params;
}

@Override
protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
    return params;
};

@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
    try {
        String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));

        return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JSONException je) {
        return Response.error(new ParseError(je));
    }
}

@Override
protected void deliverResponse(JSONObject response) {
    listener.onResponse(response);
}

PHP

$username = $_POST["username"];
$password = $_POST["password"];

echo json_encode($response);

You have to make a map, the map supports key-value type, and than you post with volley.
In php you get $variable = $_POST[“key_from_map”] to retreive it’s value in the $variable
Then you build up the response and json_encode it.

Here is a php example of how to query sql and post answer back as JSON

$response["devices"] = array();

    while ($row = mysqli_fetch_array($result)) {


        $device["id"] = $row["id"];
        $device["type"] = $row["type"];


        array_push($response["devices"], $device);  
    }

    $response["success"] = true;
    echo json_encode($response);

You can see here that the response type is JSONObject

public CustomRequest(int method, String url,Map<String, String> params, Listener<JSONObject> reponseListener, ErrorListener errorListener)

Look at the listener’s parameter!

Leave a Comment