如何使用Volley发布JSONObject并以字符串形式接收?

时间:2016-02-23 14:14:05

标签: android mobile android-volley

我正在尝试使用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

提前谢谢。

2 个答案:

答案 0 :(得分:1)

这是我使用String请求所做的。在这个例子中,我在JSON对象中发布参数。 使用http://posttestserver.com/post.php对其进行了测试。基本上覆盖超类的两个POST相关方法(Request class)getBody()和getBodyContentType()来提供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";
                    }

                };

答案 1 :(得分:0)

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

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);

                }
            });