Volley Content-Type header not updating

2020-01-31 11:18发布

I am trying to write a POST call in Volley, to send an XML body to the server. I cannot set the Content-Type header correctly.

The basic StringRequest looks like this:

StringRequest folderRequest =
        new StringRequest(Method.POST, submitInterviewUrl, myListener, myErrorListener)
    {
        @Override
        public byte[] getBody() throws AuthFailureError
        {
            String body = "some text";
            try
            {
                return body.getBytes(getParamsEncoding());
            }
            catch (UnsupportedEncodingException uee)
            {
                throw new RuntimeException("Encoding not supported: "
                        + getParamsEncoding(), uee);
            }
        }

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

I override getHeaders() to supply the Content-Type header that I want - application/xml.

That is based on the suggestions questions similar to this one:


When the request is sent, Volley has added a second Content-Type header automatically, so the headers look like this:

Content-Type: application/xml
Content-Type: application/x-www-form-urlencoded; charset=UTF-8

How do I set the correct header? Or remove the incorrect header?

I have tried tracing through the base Request code, but have been unable to find where this extra header comes from.

1条回答
贪生不怕死
2楼-- · 2020-01-31 11:48

The Content-Type header is not treated the same way as other headers by Volley. In particular, overriding getHeaders() to change the content type does not always work.

The correct way to do this is to override getBodyContentType():

    public String getBodyContentType()
    {
        return "application/xml";
    }

I found this by looking at the code for the JsonRequest class.

Delyan also mentions it in his answer to this related question:

查看更多
登录 后发表回答