简体   繁体   English

如何使用Volley将JSON发布到PHP Web服务

[英]How to post json with volley to php web service

I am trying to Post Json to my restful API with volley but it doesn't work. 我正在尝试通过齐射将Json发布到我的静态API,但是它不起作用。 So far i have tested my web service by sending a json payload through the Advance rest client app on chrome and it returns a json response.... but when i try it with Volley it returns onErrorResponse. 到目前为止,我已经通过在chrome上通过Advance rest客户端应用程序发送json负载来测试我的Web服务,并且它返回json响应....但是当我使用Volley尝试它时,它返回了onErrorResponse。 Please can someone tell me how to solve this problem, thanks in advance. 在此先感谢您能告诉我如何解决此问题。

Json payLoad: Json payLoad:

   {"country":"isreal","mobile":"009988778"}

Code

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

}

What you are doing is, you are trying to send a JSON as a part of Headers which won't work. 您正在做的是,您正在尝试将JSON作为Headers的一部分发送,但无法正常工作。

This is what you need - 这就是您需要的-

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

You need to send JSONObject as a part of request not as a part of request headers. 您需要将JSONObject作为请求的一部分而不是请求标头的一部分发送。 Try it out and let me, if it fixes the issue else we troubleshoot it. 尝试一下,让我来,如果它可以解决问题,否则我们将对其进行故障排除。

And as you already using JSONObjectRequest , you niether need to set the content type nor override getParams() until or unless you need to send some extra information in your header like AgentType, tokens etc. 而且,由于您已经在使用JSONObjectRequest ,因此您无需设置内容类型或覆盖getParams()直到或除非您需要在标头中发送一些额外的信息(例如AgentType,令牌等)。

  1. Convert object to json string. 将对象转换为json字符串。
  2. Override getBody of Volley request object 覆盖Volley请求对象的getBody
  3. Override getBodyContentType to set as json 覆盖getBodyContentType设置为json

      Gson gson = new Gson(); final String json = gson.toJson(loginDTO); GsonRequest<EmailLoginRestResponse> jsObjRequest = new GsonRequest<EmailLoginRestResponse>( Request.Method.POST, url, EmailLoginRestResponse.class, null, this.createLoginRequestSuccessListener(), this.createLoginErrorListener()){ @Override public byte[] getBody() throws AuthFailureError { return json.getBytes(); } @Override public String getBodyContentType() { return "application/json; charset=" + this.getParamsEncoding(); } }; jsObjRequest.setShouldCache(false); this.mRequestQueue.add(jsObjRequest); 

GsonRequest.java GsonRequest.java

https://github.com/ogrebgr/android_volley_examples/blob/master/src/com/github/volley_examples/toolbox/GsonRequest.java https://github.com/ogrebgr/android_volley_examples/blob/master/src/com/github/volley_examples/toolbox/GsonRequest.java

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM