Android:Volley String Request with JsonObject Params

こ雲淡風輕ζ 提交于 2019-12-12 04:31:30

问题


I have run into an issue with Volley String/JsonObject requests.

When I try to login, I want to pass json-data as parameters, but what I want to receive is a string. This causes issues because when using JsonObject request, it requires the data to be that of an JsonObject, and because the return type is of type java.lang.string it instead complains that it cannot convert type java.lang.string to jsonObject. Fine. When trying String request, the params can't be jsonObject, so that won't work... at all.

What do I do? In short I want to be able to pass JsonObject parameters and retrieve a string, is this possible?

Here's some code to help you understand my situation:

Map<String, String> postParam = new HashMap<String, String>();
postParam.put("name", mEmail);
postParam.put("password", mPassword);

RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,"http://" + getString(R.string.user_login), new JSONObject(postParam),
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                    Toast.makeText(LoginActivity.this, "Success " + response ,Toast.LENGTH_LONG).show();
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG ).show();
                Log.d("TAG" ,error.toString());
                failedLogin();

            }
        });
requestQueue.add(jsonObjectRequest);

This prompts the error

com.android.Volley.ParseError: org.json.JSONException: Value (STRING TOKEN) of type java.lang.String cannot be converted to JsonObject

and with string request you can't pass jsonObject with getParams, unfortunately!

来源:https://stackoverflow.com/questions/44145309/androidvolley-string-request-with-jsonobject-params

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!