我正在尝试使用Android Volley发布数据并接收Json Response。我有下面的代码,我似乎无法看到错误的位置,因为我在网上找到的所有代码都与此类似。我附上了android给出的消息的截图。
public String rBody = null;//Is Initialized also tried (String)null
public void loadSharedPreferencesData(){
SharedPreferences sharedPre = getSharedPreferences("userinfo", Context.MODE_PRIVATE);
final String loggedStatus = sharedPre.getString("isLogged", "0");
final String loggedUserId = sharedPre.getString("userId", "0");
String loginUrl = "http://dataUrl[![enter image description here][1]][1]/startvapp-ci/appdata/getsession/";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, loginUrl, rBody ,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response){
//returnResponse = response.toString();
//Toast.makeText(getApplicationContext(), returnResponse , Toast.LENGTH_LONG).show();
System.out.println(response);
//Toast.makeText(getApplicationContext(), "Error in Response" , Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//Save this to some global variable
Toast.makeText(getApplicationContext(), "Error in Response" , Toast.LENGTH_LONG).show();
}
}
){
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_SESS_USERID,loggedUserId);
params.put(KEY_SESS_STATUS,loggedStatus);
return params;
}
};
MySingleton.getInstance(this.getApplicationContext()).addToRequestQueue(jsonObjectRequest);
}
答案 0 :(得分:3)
该错误消息指出jsonRequest
参数的类型错误。它需要JSONObject
,但您提供String
(rBody
变量)。
如果rBody
字符串是有效的JSON字符串,那么您只需将该字符串传递给JSONObject
构造函数即可。然后将此JSONObject
传递给JsonObjectRequest
构造函数而不是rBody
。
JSONObject jsonRequest = new JSONObject(rBody);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.POST, loginUrl, jsonRequest,
new Response.Listener<JSONObject>() {
// Response Listener code here
},
new Response.ErrorListener() {
// Error Listener code here
});