PHP cURL POST returns a 415 - Unsupported Media Type

Problem solved! Here's the issue:

Sending an associative-array of headers DOES NOT WORK with cURL. There are several forums scattered around that show examples using an associative array for headers. DON'T DO IT!

The correct way (which is also scattered around the internets, but that I'm too dense to have noticed) is to construct your header key/value pairs as strings, and pass a standard array of these strings when setting the CURLOPT_HTTPHEADER option.

So in summary,

WRONG:

$headers = array(    "Accept-Encoding" =>    "gzip",
                     "Content-Type" =>       "application/json",
                     "custom_header_1" =>    "test011",
                     "custom_header_2" =>    "test012",
                     "custom_header_3" =>    "test013");

RIGHT:

$headers = array(    "Accept-Encoding: gzip",
                     "Content-Type: application/json",
                     "custom_header_1: test011",
                     "custom_header_2: test012",
                     "custom_header_3: test013");

I hope this comes in handy to some other noble doofus down the road before they waste as much time debugging as I did.

If I had to guess, I would assume that the same rule applies to the POST body key/value pairs as well, which is why @drew010 's comment about using http_build_query() or json_encode() to stringify your message body is a great idea as well.

Thanks to everyone for your very useful comments, and for you time and consideration. In the end, a side by side comparison of the http traffic (captured via Wireshark) revealed the issue.

Thanks!


I think the problem is that you are passing an array as the CURLOPT_POSTFIELDS option. By passing an array, this forces the POST request to use multipart/form-data when the server is probably expecting application/x-www-form-urlencoded.

Try changing

curl_setopt($request, CURLOPT_POSTFIELDS, $this->body);

to

curl_setopt($request, CURLOPT_POSTFIELDS, http_build_query($this->body));

See http_build_query for more information and also this answer: My cURL request confuses some servers?

Tags:

Php

Curl

Jboss

Post