CURL works for my REST API, but Guzzle not

I am trying to connect my Laravel infrastructure to my server using Guzzle. Each GET request is without parameters, but I have problems with POST.

This query using cURL works fine:

curl -i -X POST -H 'Content-Type: application/json' -d '{"email":" user@domain.com ", "pwd":"xxxxxx"}' http://www.example.com:1234/rest/user/validate 

And here is what I tried to implement using Guzzle:

 $response = GuzzleHttp\post('http://www.example.com:1234/rest/user/validat', [ 'headers' => ['Content-Type' => 'application/json'], 'body' => ['{"email":" user@domain.com ", "pwd":"xxxxxx"}'] ]); print_r($response->json()); 

When I make a request, I get the following error:

 [status code] 415 [reason phrase] Unsupported Media Type 

I think this is due to the body , but I do not know how to solve it.

Any idea?

+6
source share
3 answers

There is no need to have square brackets around the body value. Also, make sure there is an Accept header. You should use this instead:

 $response = GuzzleHttp\post('http://www.example.com:1234/rest/user/validat', [ 'headers' => ['Content-Type' => 'application/json', 'Accept' => 'application/json'], 'body' => '{"email":" user@domain.com ", "pwd":"xxxxxx"}' ]); print_r($response->json()); 
+7
source

Guzzle 6 removed the json() method due to PSR-7 compliance (link https://github.com/guzzle/guzzle/issues/1106 ). Therefore, if you are using an earlier version, the answer to the lower part may work; for version 6 users use instead:

 $response = GuzzleHttp\post('http://www.example.com:1234/rest/user/validat', [ 'headers' => ['Content-Type' => 'application/json', 'Accept' => 'application/json'], 'body' => '{"email":" user@domain.com ", "pwd":"xxxxxx"}' ]); print_r(json_decode($response->getBody(), true)); 
+1
source

removing the space between "Content-Type: application / json" and changing it to "Content-Type: application / json" worked for me

0
source

Source: https://habr.com/ru/post/972828/


All Articles