phprestcurllaravel-4guzzle

cURL works for my REST API but Guzzle not


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":"user@domain.com", "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":"user@domain.com", "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?


Solution

  • 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":"user@domain.com", "pwd":"xxxxxx"}'
    ]);     
    print_r($response->json());