问题
I have a SearchActivity . i must send a parameter like search keyword to server and receive JsonArray .
I used this code for JsonArrayRequest :
JsonArrayRequest stringRequest = new JsonArrayRequest(Request.Method.POST, url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
pDialog.dismiss();
Log.e("response : ",response.toString());
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
pDialog.dismiss();
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new Hashtable<String, String>();
params.put("test", "ok");
return params;
}
};
AppController.getInstance().addToRequestQueue(stringRequest);
in server PHP file :
$keyword= @$_POST["test"];
if($keyword=="ok")
{
echo'
[
{
"name":"name 1 ",
"img":"1.jpg",
"info":"hello",
"id":"eee"
},
{
"name":"name 2",
"img":"2.jpg",
"info":"hello",
"id":"222"
}
]
';
}
But server dont send anything for app
i tested it by StringRequest it work fine but in JsonArrayRequest it not work
When i use JsonArrayRequest it seem parameters not seted
pls help
回答1:
Why you don't use StringRequest?
If your response is JsonArray or JsonObject you can get it from StringResponse as well.
String response;
JSONArray arrayResponse = new JSONArray(response);
回答2:
If your project uses mcxiaoke's library, you will find inside JsonArrayRequest.java file there's a constructor as below
public JsonArrayRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONArray> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
errorListener);
}
Use this for your request.
If your app uses Google's volley library (not JAR file), you will need to add that constructor into JsonArrayRequest.java file, or you may try using getBody() instead of getParams().
UPDATE: use the following sample
...
JSONObject requestBody = new JSONObject();
try {
requestBody.put("key1", "value1");
requestBody.put("key2", "value2");
JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST, url, requestBody, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
// do something
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// do something
}
};
// Executes request
requestQueue.add(request);
} catch (JSONException e) {
// do something
}
...
回答3:
you can follow below link is much similar to you question.
Why is Volley's onResponse not called
来源:https://stackoverflow.com/questions/37510810/volley-jsonarrayrequest-can-not-send-parameter-to-server