Reputation: 8075
I would include examples, but none of dozens of examples I have tried seem to work. If I try to use requestJsonObject, I get an error on the response saying that it can't put a JSONArray into a JSONObject. If I try to use JSONArray, it can't seem to handle a post parameters. I found a post that claimed they updated something to allow JSONObject to be passed into JSONArray, but can't find a damn thing anywhere as to where or how I get it in my code. All that I want to do is send a simple restful post, and get a json response. I'm looking through post after post after post and I'm not familiar enough with java to understand some of these more complex answers, find ones with no parameters, or find ones that are trying to push a JSONObject into JsonArrayRequest (which throws an error for me) How in the hell do you get it to work in android?!?! Here's the two methods I have tried
private void makeArrayRequest(String setSwitch)
{
try {
Map<String, String> params = new HashMap();
params.put("func", setSwitch);
JSONArray parameters = new JSONArray(params);
DisplayToast("Sending: " + setSwitch);
JsonArrayRequest jsonRequest = new JsonArrayRequest(
Request.Method.POST, url, parameters,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
DisplayText("Response: " + response.toString());
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//error.printStackTrace();
DisplayText("Error:"+error.getMessage());
}
}
);
Volley.newRequestQueue(this).add(jsonRequest);
} catch(JSONException e) {
// this ends up getting thrown because of the HASH input
DisplayText("ArrErr:"+e.getMessage());
}
}
private void makeObjectRequest(String setSwitch)
{
DisplayToast("Sending: " + setSwitch);
Map<String, String> params = new HashMap();
params.put("func", setSwitch);
JSONObject parameters = new JSONObject(params);
JsonObjectRequest jsonRequest = new JsonObjectRequest(
Request.Method.POST, url, parameters,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
DisplayText("Response: " + response.toString());
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//this ends up getting thrown because of JSONArray response?
DisplayText("Error:"+error.getMessage());
}
}
);
Volley.newRequestQueue(this).add(jsonRequest);
}
Upvotes: 0
Views: 958
Reputation: 8075
The differences between the java and the PHP was the problem. PHP handles POST data differently and wasn't getting the values because of the way they were encoded.
The work-around is to decode them from php://input
$post = json_decode(file_get_contents("php://input"), true);
as outlined here
Upvotes: 1