如何将 json 与 volley 发布到 php web 服务

mis*_*ish 0 php java android json android-volley

我正在尝试使用 volley 将 Json 发布到我的宁静 API,但它不起作用。到目前为止,我已经通过 Chrome 上的 Advance rest 客户端应用程序发送一个 json 有效负载来测试我的 Web 服务,它返回一个 json 响应......但是当我用 Volley 尝试它时,它返回 onErrorResponse。请有人告诉我如何解决这个问题,在此先感谢。

JSON 有效载荷:

   {"country":"isreal","mobile":"009988778"}
Run Code Online (Sandbox Code Playgroud)

代码

 private void processLogin() {
    showProgressDialog();
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
            Const.LOGIN_URL, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.i("JSON response", "JSON Posting" + response.toString());
            hideProgessDialog();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            VolleyLog.d(ERROR_TAG, "Error: " + volleyError.getMessage());
            hideProgessDialog();
        }
    }){

    @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            return headers;
    }

    @Override
    protected Map<String, String> getParams(){
        String country_value = country.getSelectedItem().toString();
        String mobile_value = mobile.getText().toString();
        Map<String, String> params = new HashMap<>();
        params.put("country",country_value);
        params.put("mobile", mobile_value);
        return params;
    }
    };

    AppController.getInstance().addToRequestQueue(jsonObjReq, login_tag);

}
Run Code Online (Sandbox Code Playgroud)

Var*_*oid 5

您正在做的是,您试图将 JSON 作为 Headers 的一部分发送,但这是行不通的。

这就是你需要的——

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
            Const.LOGIN_URL, **->YOUJSONOBJECTHERE<-**, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.i("JSON response", "JSON Posting" + response.toString());
            hideProgessDialog();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            VolleyLog.d(ERROR_TAG, "Error: " + volleyError.getMessage());
            hideProgessDialog();
        }
    });
Run Code Online (Sandbox Code Playgroud)

您需要JSONObject作为请求的一部分而不是请求标头的一部分发送。尝试一下,让我来解决,如果它解决了问题,我们将对其进行故障排除。

并且由于您已经在使用JSONObjectRequest,您无需设置内容类型或覆盖,getParams()直到或除非您需要在您的标头中发送一些额外的信息,如 AgentType、令牌等。