ciungulete's avatar

Http client post raw content

Using Laravel 7.6 and it's built-in HTTP Client.

I'm trying to send a simple POST request with body in Raw JSON format to my other domain but no luck:

$response = Http::post('https://example.com', [ 'body' => '{ test: 1 }' ]); I get 400 Bad Request - Client error - because my server expects body as a mandatory.

What am I missing here?

0 likes
6 replies
MichalOravec's avatar
$response = Http::withHeaders([
    'Accept' => 'application/json'
])->post('https://example.com', [ 
    'body' => [
        'test' => 1 
    ] 
]);
ciungulete's avatar

Don't work.

Can anyone explain to me why this is working

$response = Http::contentType("text/plain")->send('POST','https://example.com', [
    'body' => 'FETCH....'
])->json();

and this is not work

$response = Http::contentType("text/plain")->post('https://example.com', [
    'body' => 'FETCH....'
])->json();
2 likes
MichalOravec's avatar

@ciungulete Different is $bodyFormat you can see it here

https://github.com/laravel/framework/blob/master/src/Illuminate/Http/Client/PendingRequest.php#L397

https://github.com/laravel/framework/blob/master/src/Illuminate/Http/Client/PendingRequest.php#L456

So in the post method your array go to that $bodyFormat key

$response = Http::contentType("text/plain")->bodyFormat('none')->post('https://example.com', [
    'body' => 'FETCH....'
])->json();

Also there are three options for that ->bodyFormat('json') ->bodyFormat('form_params') ->bodyFormat('multipart')

But instead of these you can use ->asJson() ->asForm() ->asMultipart()

2 likes
ciungulete's avatar

If I use bodyFormat('none') the body was not sent... I will use

$response = Http::contentType("text/plain")->send('POST','https://example.com', [
    'body' => 'FETCH....'
])->json();

Thanx

1 like

Please or to participate in this conversation.