HTTP client request header - Content-Type

When setting content type, ’ charset=UTF-8’ is automatically appended when submitting the request.

I have tried via setHeader():

$request = new Client()->createRequest()->setHeaders(['Content-type' => 'application/json']);

Have also tried via setOption:

$request = new Client()->createRequest()->setOptions([
    CURLOPT_HTTPHEADER => ['Content-Type: application/json' ]
]);

When view in debug, the content type is Content-Type: application/json; charset=UTF-8

Is there an option to exclude the encoding string from appending to content-type?

did you try setting the headers in the request method

https://www.yiiframework.com/extension/yiisoft/yii2-httpclient/doc/api/2.0/yii-httpclient-client#get()-detail

Yes, have tried. When calling $request->getHeaders() it’s still showing application/json; charset=UTF-8 for content-type.

sorry maybe I was not clear did you try passing the headers in your method call for example

$request = new Client()->createRequest()->setOptions([
    CURLOPT_HTTPHEADER => ['Content-Type: application/json' ]
]);


$request->get('/url', null, ['Content-Type' => 'application/json']);

Isn’t this same as what I have tried? See second code snippet in original post.

Also your code dosn’t work, isn’t get() and post() methods for Client, not Request?

This is what I have also tried:

$request = new Client()
   ->post(url, $data, ['Content-Type' => 'application/json'])
   ->setOptions([
        CURLOPT_HTTPHEADER => ['Content-Type: application/json' ]
    ]);

The content type in request header now becomes application/x-www-form-urlencoded; charset=UTF-8.

Is there a solution for this or is this a bug?

Hello. Did you found a solution to this issue?
I am using httpclient v2.0.9
Setting headers this way
$request = $client->createRequest()->setHeaders([‘Content-Type’ => ‘application/json’]);
And im getting this header in request
Content-Type: application/x-www-form-urlencoded; charset=UTF-8

I ended up calling native php curl functions.

You can try to setup the request format to Json.

$request = new Client()
   ->post(url, $data)
   ->setFormat(Client::FORMAT_JSON)
   ->send();
1 Like

Thanks, this did it for me. I would like to recommend this answer to anyone who is trying to send a post request with content-type json or, in postman terms, raw body json.

found a solution to custom header for any formatter

    $request = $client->createRequest();
    $client->getFormatter(Client::FORMAT_XML)->contentType='application/rss+xml';
    $response = $request
      ->setMethod('POST')
      ->setUrl($url)
      ->setFormat(Client::FORMAT_XML)
      ->setHeaders([$authorization])
      ->setData($data)
      ->send();