Android Volley发布请求。如何设置实体?

时间:2014-10-24 09:32:54

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

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

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

现在我想在排球请求中更改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);

1 个答案:

答案 0 :(得分:0)

您只需覆盖getBody(),就像在StringRequest中重写了getBodyContentType一样

示例代码

String body = "test body";

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