Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Volley Content-Type header not updating

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:

  • Android Volley Post Request Header not changing

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.

like image 408
Richard Le Mesurier Avatar asked Oct 07 '14 22:10

Richard Le Mesurier


1 Answers

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:

  • how to execute PUT request in Android Volley?
like image 117
Richard Le Mesurier Avatar answered Oct 09 '22 18:10

Richard Le Mesurier