Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

android - Send post request using Volley and receive in PHP

I am trying to use volley in my project to handle all my HTTP request since it's the most efficient one as far as I know. So I started to learn volley by following this AndroidHive tutorial.

My first GET request was successful. Then I moved on to POST request and I failed. I saw on Stack Overflow many people had problems combining post request of volley with PHP. I believe we cannot access it using the normal way that is $_POST[""] as volley sends a JSON object to the URL which we specify.

There were lots of solutions which I tried but didn't succeed. I guess there should be a simple and standard way of using volley with PHP. So I would like to know what do I need to do in order to receive the json object sent by volley in my PHP code.

And also how do I check if volley is really sending a JSON object?

My volley code to send simple post request:

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
                url, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(TAG, response.toString());
                        pDialog.hide();
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        pDialog.hide();
                    }
                }) {

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("name", "Droider");
                return params;
            }

        };

// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

My PHP code to receive json object: (I am pretty sure this is the wrong way, I am not that good in PHP)

<?php
    $jsonReceiveData = json_encode($_POST);
    echo $jsonReceivedData;
?>

I tried lots of ways of accepting JSON object in PHP like this one as well echo file_get_contents('php://input');

The Result

null

EDIT (The correct way thanks to Georgian Benetatos)

I created the class as you mentioned the class name is CustomRequest which is as follows:

import java.io.UnsupportedEncodingException;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;

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> reponseListener, ErrorListener errorListener) {
            super(Method.GET, url, errorListener);
            this.listener = reponseListener;
            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 void deliverResponse(JSONObject response) {
        listener.onResponse(response);
    }

    @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));
            }
    }

}

Now in my activity I called the following:

String url = some valid url;
Map<String, String> params = new HashMap<String, String>();
params.put("name", "Droider");

CustomRequest jsObjRequest = new CustomRequest(Method.POST, url, params, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    Log.d("Response: ", response.toString());
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError response) {
                Log.d("Response: ", response.toString());
            }
        });
        AppController.getInstance().addToRequestQueue(jsObjRequest);

My PHP code is as follow:

<?php
$name = $_POST["name"];

$j = array('name' =>$name);
echo json_encode($j);
?>

Now its returning the correct value:

Droider
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...