如何使用Volley发布JSONObject并接收字符串? [英] How can I POST a JSONObject using Volley and receive in a String?
问题描述
我正在尝试使用Volley发布JSONObject.服务器响应很可能不是JSONObject类型.有什么想法或解决方法吗?这是我的代码:
I'm trying to post an JSONObject using Volley. Most probably, the servers response is not type JSONObject. Any ideas or workaround? This is my code:
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);
这是我收到的错误响应:
and this is the error response I'm receiving :
com.android.volley.ParseError: org.json.JSONException: Value OK of type java.lang.String cannot be converted to JSONObject
谢谢.
推荐答案
这是我使用String请求所做的事情.在此示例中,我在JSON对象中发布了参数.使用 http://posttestserver.com/post.php 对其进行了测试.基本上重写超类(请求类)的两个与POST相关的方法getBody()和getBodyContentType()来提供帖子数据.
Here's what I did using String request. In this example, I'm posting parameters inside JSON object. Tested it out using http://posttestserver.com/post.php. Basically override two POST related methods of the super class (Request class) getBody() and getBodyContentType() to supply post data.
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";
}
};
这篇关于如何使用Volley发布JSONObject并接收字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!