SOLVED: zf2 “Cannot handle content type ‘application/json’ automatically”

I have to admit, this was quite annoying to resolve and didn’t really have to be an issue in the first place.

I’m using Zend Framework 2.3 and the following was my code:

use Zend\Http\Client;
use Zend\Http\Request;
...
        $client = new Client($url);
        $client
            ->setHeaders([
                'Content-Type' => 'application/json',
            ])
            ->setOptions(['sslverifypeer' => false])
            ->setMethod('POST')
            ->setParameterPost($params);

The problem?

I kept getting the following exception thrown: “Cannot handle content type ‘application/json’ automatically” at vendor/zendframework/zendframework/library/Zend/Http/Client.php line 1219.

I googled and googled and googled and found a BUNCH of different examples on how to do the exact same thing but none of them really resolved this issue for me.  I finally decided to use Kint to debug $client and see what methods are available to me.  I saw the setRawBody method and thought to myself… That’s gotta be it!

The following is the code that works:

use Zend\Http\Client;
use Zend\Http\Request;
use Zend\Json\Json;
...
        $client = new Client($url);
        $client
            ->setHeaders([
                'Content-Type' => 'application/json',
            ])
            ->setOptions(['sslverifypeer' => false])
            ->setMethod('POST')
            ->setRawBody(Json::encode($params));

I hope this helps!

5 thoughts on “SOLVED: zf2 “Cannot handle content type ‘application/json’ automatically”

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.