HTTP client request header - Content-Type


(C) #1

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?


(Alirz23) #2

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


(C) #3

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


(Alirz23) #4

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']);

(C) #5

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.


(C) #6

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


(r45boon) #7

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


(C) #8

I ended up calling native php curl functions.


(i-lie) #9

You can try to setup the request format to Json.

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