Home » Php » php – cURL works for my REST API but Guzzle not

php – cURL works for my REST API but Guzzle not

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am trying to connect my Laravel framework to my server using Guzzle. Every GET request without parameters but I have problems with POST.

This request using cURL works fine:

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

And this is what I have tried to implement with Guzzle:

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

When I make the request, I get the next error:

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

I think is something related to body but I don’t know how to solve it.

Any idea?

How to&Answers:

There’s no need to have the square brackets around the body value. Also, make sure there is an Accept header defined. 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":"[email protected]", "pwd":"xxxxxx"}'
]);     
print_r($response->json());

Answer:

Guzzle 6 removed the json() method because of PSR-7 compliance (ref. https://github.com/guzzle/guzzle/issues/1106). So if you’re using an earlier version, lowerends’ answer may work; for version 6 users, use this instead:

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

Answer:

removing the space between ‘Content-Type: application/json’ and modify it to ‘Content-Type:application/json’ worked for me