【问题标题】:Android Volley Post Request. How to setEntity?Android Volley 发布请求。如何设置实体?
【发布时间】:2014-12-20 03:15:00
【问题描述】:

我在代码中使用了 HttpPost,我在其中添加了这样的实体:

String bodyContent = ".......";
HttpPost httpost = new HttpPost(url);
StringEntity se = new StringEntity(bodyContent);
httpost.setEntity(se);

现在我想更改 Volley Request 中的 HttpPost。 如何设置setEntity? 我不明白如何插入字符串 bodyContent。 我应该使用其他方法吗?

    boolean contentType = true/false;  

    //new post request in to volley
    StringRequest postRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>()
            {
                @Override
                public void onResponse(String response) {
                    // response
                    Log.d("Error.Response", "OK");
                }
            },
            new Response.ErrorListener()
            {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // error
                    Log.d("Error.Response", "KO");
                }
            }
        ) {
       //add body content-type
        @Override
        public String getBodyContentType() {
            if (contentType) {
                return "application/json; charset=utf-8";
            } else {
                return "text/plain; charset=utf-8";
            }
        }
        //add header
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError 
        {
            Map<String, String>  params = new HashMap<String, String>();
            params.put("VLHASH", "464646");
            return params;
        }

        @Override
        protected Map<String, String> getParams()
        {
            Map<String, String>  params = new HashMap<String, String>();
            params.put("name", "Alif");
            params.put("domain", "http://itsalif.info");
            return params;
        }
    };
    queue.add(postRequest);

【问题讨论】:

  • 你找到解决问题的决定了吗?

标签: android http-post content-type android-volley


【解决方案1】:

你只需要覆盖 getBody() 就像你在 StringRequest 中覆盖了 getBodyContentType 一样

示例代码

String body = "test body";

 @Override
    public byte[] getBody() throws AuthFailureError {
        return body.getBytes();
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多