Reputation: 10342
I am using the Volley framework with JsonObjectRequest request. I am using
JsonObjectRequest loginRequest = new JsonObjectRequest(b.toString(), params,
new Listener<JSONObject>() {},
new Response.ErrorListener() {});
The params
variable contains the parameters and it is a JSONObject.
The problem is that I cannot access any of these variables in my PHP code. $_POST or $_REQUEST variables gives me nothing.
I also tried something like below but no luck.
$data = json_decode(file_get_contents("php://input"));
Upvotes: 3
Views: 1566
Reputation: 81
I encountered the same problem while using Volley with my PHP API. Turns out, a JSONObject
of params is sent along as JSON. Therefore, PHP $_POST won't recognize it because it isn't in the format: param1=value1¶m2=value
To see for yourself try: print file_get_contents("php://input");
The solution for me was to create a workaround class that extends Request<JSONObject>
instead of using JsonObjectRequest
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.toolbox.HttpHeaderParser;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Custom Request Class for JSON
*/
public class CustomRequest extends Request<JSONObject> {
private List params; // the request params
private Response.Listener<JSONObject> listener; // the response listener
public CustomRequest(int requestMethod, String url, List params,
Response.Listener<JSONObject> responseListener, Response.ErrorListener errorListener) {
super(requestMethod, url, errorListener); // Call parent constructor
this.params = params;
this.listener = responseListener;
}
// We have to implement this function
@Override
protected void deliverResponse(JSONObject response) {
listener.onResponse(response); // Call response listener
}
// Proper parameter behavior
@Override
public Map <String, String> getParams() throws AuthFailureError {
Map <String, String> map = new HashMap <String, String>();
// Iterate through the params and add them to our HashMap
for (BasicNameValuePair pair: params) {
map.put(pair.getName(), pair.getValue());
}
return map;
}
// Same as JsonObjectRequest#parseNetworkResponse
@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));
}
}
}
Upvotes: 7