我正在尝试根据发送的数据从服务器获取响应,我能够从服务器获取响应,但是服务器似乎未在getParams()中接收值。
String url = "myUrl";
RequestQueue queue = Volley.newRequestQueue(getContext());
schoolContributeList = new ArrayList<>();
JsonArrayRequest jsonRequest = new JsonArrayRequest(Request.Method.POST, url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray ja) {
try {
for (int i = 0;i < ja.length();i++) {
JSONObject school = ja.getJSONObject(i);
String schoolId = school.getString("id");
String schoolName = school.getString("name");
universityItem schoolItem = new universityItem(schoolName, schoolId);
Toast.makeText(getContext(),schoolId , Toast.LENGTH_SHORT).show();
schoolContributeList.add(schoolItem);
schoolContributeAdapter = new universityAdapter(getContext(), schoolContributeList);
schoolContributeSpinner.setAdapter(schoolContributeAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error)
{
Log.i("error", error.toString());
Toast.makeText(getContext(), "no response", Toast.LENGTH_SHORT).show();
}
}){
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
Toast.makeText(getContext(), selectedUniversityItem.getmUniversityValue(), Toast.LENGTH_SHORT).show();
params.put("schoolUniversity", selectedUniversityItem.getmUniversityValue());
params.put("key", key);
return params;
}
};
queue.add(jsonRequest);
最佳答案
在这种情况下,我建议的方法是在代码的URL中传递参数,并删除getParams()方法。
因此,修改后的代码看起来像;
String url = "myUrl";
RequestQueue queue = Volley.newRequestQueue(getContext());
schoolContributeList = new ArrayList<>();
JsonArrayRequest jsonRequest = new JsonArrayRequest(Request.Method.POST, url+"?schoolUniversity="+selectedUniversityItem.getmUniversityValue()+"&key="+key,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray ja) {
try {
for (int i = 0;i < ja.length();i++) {
JSONObject school = ja.getJSONObject(i);
String schoolId = school.getString("id");
String schoolName = school.getString("name");
universityItem schoolItem = new universityItem(schoolName, schoolId);
Toast.makeText(getContext(),schoolId , Toast.LENGTH_SHORT).show();
schoolContributeList.add(schoolItem);
schoolContributeAdapter = new universityAdapter(getContext(), schoolContributeList);
schoolContributeSpinner.setAdapter(schoolContributeAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error)
{
Log.i("error", error.toString());
Toast.makeText(getContext(), "no response", Toast.LENGTH_SHORT).show();
}
}){
};
queue.add(jsonRequest);
希望这会起作用。祝好运 :)