【问题标题】:How can I POST a JSONObject using Volley and receive in a String?如何使用 Volley 发布 JSONObject 并接收字符串?
【发布时间】:2016-02-23 14:14:05
【问题描述】:

我正在尝试使用 Volley 发布 JSONObject。很可能,服务器响应不是 JSONObject 类型。有什么想法或解决方法吗? 这是我的代码:

 RequestQueue requestQueue = Volley.newRequestQueue(context);

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonobject, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

            Build.logError("Response:" + response);

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            Build.logError("Error: " + volleyError);


        }
    });

    requestQueue.add(jsonObjectRequest);

这是我收到的错误响应:

com.android.volley.ParseError: org.json.JSONException: Value OK of type java.lang.String cannot be converted to JSONObject

提前谢谢你。

【问题讨论】:

  • 嗨 NJ Nilesh,响应是我根据我的请求获得的代码行:com.android.volley.ParseError: org.json.JSONException: Value OK of type java.lang.String cannot be转换为 JSONObject
  • 你可以使用StringRequest
  • 你的响应字符串或Json是什么?如果json使用String.Valueof(response)查看响应
  • StringRequest strReq = new StringRequest(Request.Method.POST, url, jsonobject, new Response.Listener&lt;String&gt;() 试试这个

标签: android mobile android-volley


【解决方案1】:

这是我使用字符串请求所做的。在此示例中,我在 JSON 对象中发布参数。 使用http://posttestserver.com/post.php 对其进行了测试。基本上重写了超类(Request类)getBody()和getBodyContentType()的两个POST相关方法来提供post数据。

RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
                final JSONObject jsonObject = new JSONObject();
                jsonObject.put("fName", "First");
                jsonObject.put("lName", "Last");
                jsonObject.put("age", 11);
                jsonObject.put("ts", System.currentTimeMillis());
                StringRequest stringRequest = new StringRequest(Request.Method.POST, uri,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                System.out.println("Response from server: " + response);
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        NetworkResponse response = error.networkResponse;
                        if (response != null) {
                            System.out.println("error code: " + response.statusCode);
                        }
                    }
                }) {
                    @Override
                    public byte[] getBody() throws AuthFailureError {
                        return jsonObject.toString().getBytes();
                    }

                    @Override
                    public String getBodyContentType() {
                        return "application/json";
                    }

                };

【讨论】:

    【解决方案2】:

    您必须编写自定义请求..请尝试以下一个

    import java.io.UnsupportedEncodingException;
    
    import java.util.Map;
    
    import com.android.volley.AuthFailureError;
    import com.android.volley.DefaultRetryPolicy;
    import com.android.volley.NetworkResponse;
    import com.android.volley.Request;
    import com.android.volley.Response;
    import com.android.volley.RetryPolicy;
    import com.android.volley.toolbox.HttpHeaderParser;
    public class ServerStatusRequestObject extends Request<String> {
    
    private final Response.Listener mListener;
    private String mBody;
    private String mContentType;
    private HashMap mCustomHeaders;
    
    public ServerStatusRequestObject(int method, String url,
            HashMap customHeaders, String body, Response.Listener listener,
            Response.ErrorListener errorListener) {
    
        super(method, url, errorListener);
        mCustomHeaders = customHeaders;
        mBody = body;
        mListener = listener;
        mContentType = "application/json";
    
        if (method == Method.POST) {
            RetryPolicy policy = new DefaultRetryPolicy(5000, 0, 5);
            setRetryPolicy(policy);
        }
    }
    
    public ServerStatusRequestObject(String url, HashMap customHeaders,
            Response.Listener listener, Response.ErrorListener errorListener) {
    
        super(Method.GET, url, errorListener);
        mCustomHeaders = customHeaders;
        mListener = listener;
        mContentType = "application/x-www-form-urlencoded";
    }
    
    @Override
    protected Response parseNetworkResponse(NetworkResponse response) {
        String json = null;
        try {
            json = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return Response.success(json,
                HttpHeaderParser.parseCacheHeaders(response));
    }
    
    @Override
    public Map getHeaders() throws AuthFailureError {
        if (mCustomHeaders != null) {
            return mCustomHeaders;
        }
        return super.getHeaders();
    }
    
    @Override
    public byte[] getBody() throws AuthFailureError {
        return mBody.getBytes();
    }
    
    @Override
    public String getBodyContentType() {
        return mContentType;
    }
    
    public String getContentType() {
        return mContentType;
    }
    
    public void setContentType(String mContentType) {
        this.mContentType = mContentType;
    }
    
    @Override
    protected void deliverResponse(String arg0) {
        // TODO Auto-generated method stub
        mListener.onResponse(arg0);
    }
    

    }

    这样使用

            ServerStatusRequestObject jsonObjReq = new ServerStatusRequestObject(
                Method.POST, Urls.logout, headers, json.toString(),
                new Response.Listener<String>() {
    
                    @Override
                    public void onResponse(String arg0) {
                        // TODO Auto-generated method stub
                        Common.stopProgressDialog();
                        System.out.println("string response = " + arg0);
                        Toast.makeText(MainActivity.this, "Logout success",
                                Toast.LENGTH_LONG).show();
                        Common.savePref(MainActivity.this, Constants.sessionId,
                                null);
                    }
                }, new Response.ErrorListener() {
    
                    @Override
                    public void onErrorResponse(VolleyError arg0) {
                        // TODO Auto-generated method stub
                        Common.stopProgressDialog();
                        System.out.println("error = " + arg0);
    
                    }
                });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-09
      • 1970-01-01
      相关资源
      最近更新 更多