android-volley - 如何使用 android volley JsonObjectRequest 从 php 获取字符串响应?

标签 android-volley android-json jsonexception jsonobjectrequest

实际上,当我们调用 API 并以 JSON 格式发送请求时,我们期望响应也采用 JSON 格式。 但是这里后端团队以字符串格式向我发送响应,因此我的 onErrorResponse () 方法被调用。这里我的状态代码是200。但是由于响应的格式没有执行onResponse()方法。那么你能帮我处理一下吗?可能我必须在这里使用 CustomRequest 。任何建议将不胜感激。谢谢

public class SampleJsonObjTask {
    public static ProgressDialog progress;
    private static RequestQueue queue;
    JSONObject main;
    JsonObjectRequest req;
    private MainActivity context;
    private String prd,us,ver,fha,ve,ves,sz,cat,pa,h,t,en,pha,pur,dip;
    public SampleJsonObjTask(MainActivity context, JSONObject main) {

        progress = new ProgressDialog(context);
        progress.setMessage("Loading...");
        progress.setCanceledOnTouchOutside(false);
        progress.setCancelable(false);
        progress.show();
        this.context = context;
        this.main = main;
         ResponseTask();
    }


    private void ResponseTask() {
        if (queue == null) {
            queue = Volley.newRequestQueue(context);
        }
        req = new JsonObjectRequest(Request.Method.POST, "", main,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        progress.dismiss();
                        Log.e("response","response--->"+response.toString());
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                progress.dismiss();//error.getMessage()
                /*back end team sending me response in String format therefore my onErrorResponse () method get called. Here my status code is 200.*/
            }

        })

        {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("Content-Type", "application/json");
                return params;
            }
        };
        req.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, 1f));
        queue.add(req);

    }

}

这里响应是字符串格式,值正常,

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

最佳答案

您可以使用StringRequest来实现:

StringRequest request = new StringRequest(StringRequest.Method.POST, url, new Response.Listener<String>() {
  @Override
  public void onResponse(String response) { }
}, new Response.ErrorListener() {
  @Override
  public void onErrorResponse(VolleyError error) {
  }
}) {
  @Override
  public String getBodyContentType() {
    return "application/json; charset=utf-8";
  }

  @Override
  public byte[] getBody() {
    try {
      JSONObject jsonObject = new JSONObject();
      /* fill your json here */
      return jsonObject.toString().getBytes("utf-8");
    } catch (Exception e) { }

    return null;
  }
};

关于android-volley - 如何使用 android volley JsonObjectRequest 从 php 获取字符串响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50344562/

相关文章:

php - Android JSON 仅在 Froyo 上运行,不适用于更高版本

android - 当用户到达底部时从 JSON 动态填充 ListView

android - 检查 JSONObject 键是否存在

android - 使用 Glide 库渲染的图像不正确

android - Android 中的 PATCH 动词(OkHttp、Volley、Retrofit...)

android:从嵌套的 JSON 对象中检索值到列表类型

Android - 从服务器获取响应时验证 JSON 以避免 JSONException

android - 不显示带有响应的传入数据

android - 清除 volley 缓存需要使哪个 url 失效?

java - java.lang.String类型的JSON异常值连接无法转换为JSONArray