Volley Content-Type header not updating
Asked Answered
W

1

6

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.

Woodhouse answered 7/10, 2014 at 22:41 Comment(0)
W
27

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:

Woodhouse answered 7/10, 2014 at 22:50 Comment(2)
You saved the day, because as you mentioned, getHeaders() doesn't always workCoombs
Saved me, I was trusting the getHeaders will override the getBodyContentType provided value.Zandra

© 2022 - 2024 — McMap. All rights reserved.