使用Volley Library将数据发送到JSONObjectRequest中的服务器。错误

时间:2015-12-10 09:44:05

标签: php android json android-volley

我试图使用Volley库的JSONObjectRequest将一些值传递给服务器。但不知何故,数据没有被发送到服务器,并且应该接收数据的服务器端脚本的变量是空的。 这是JSONObjectRequest代码

        JSONObject obj = new JSONObject();

    try {
            obj.put("userid", "userid");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // making fresh volley request and getting json
        JsonObjectRequest jsonReq = new JsonObjectRequest(Method.POST,
                URL_FEED, obj, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                VolleyLog.d(TAG, "Response: " + response.toString());
                Log.d(String.valueOf(getApplicationContext()),"Response generated");
                if (response != null) {
                    parseJsonFeed(response);
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                Log.d("Error - >",error.getMessage());
                Toast.makeText(getApplicationContext(),"Error is -->> " + error.getMessage(),Toast.LENGTH_LONG).show();
            }
        });

php方面获取变量

$userid = $_POST['userid'];

1 个答案:

答案 0 :(得分:1)

通过将JSONObjectRequest更改为StringRequest然后将Onresponse String转换为JSONObject来使其工作

// making fresh volley request and getting json
        StringRequest jsonReq = new StringRequest(Method.POST,
                URL_FEED, new Response.Listener<String>() {

            @Override
            public void onResponse(String s) {
                VolleyLog.d(TAG, "Response: " + s.toString());
                JSONObject response = null;
                try {
                    response = new JSONObject(s);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                Log.d(String.valueOf(getApplicationContext()), "Response generated");
                if (response != null) {
                    parseJsonFeed(response);
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                Log.d("Error - >",error.getMessage());
                Toast.makeText(getApplicationContext(),"Error is -->> " + error.getMessage(),Toast.LENGTH_LONG).show();
            }
        }) {
            @Override
            public Map<String, String> getParams(){
                Map<String, String> params = new HashMap<String, String>();
                params.put("userid", userid);
                return params;

            }
        };