Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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":"[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?

like image 379
marc_aragones Avatar asked Jul 25 '14 11:07

marc_aragones


People also ask

Is guzzle using cURL?

Guzzle has historically only utilized cURL to send HTTP requests. cURL is an amazing HTTP client (arguably the best), and Guzzle will continue to use it by default when it is available. It is rare, but some developers don't have cURL installed on their systems or run into version specific issues.

Is guzzle better than cURL?

It provides easy user interface. Guzzle can use various kinds of HTTP clients .

How do I get guzzle response?

As described earlier, you can get the body of a response using the getBody() method. Guzzle uses the json_decode() method of PHP and uses arrays rather than stdClass objects for objects. You can use the xml() method when working with XML data.

What is guzzle HTTP client?

Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services. Simple interface for building query strings, POST requests, streaming large uploads, streaming large downloads, using HTTP cookies, uploading JSON data, etc...


2 Answers

This way it works

'Accept' => '*/*'

Good luck!

like image 72
Melqui Franco Avatar answered Oct 22 '22 01:10

Melqui Franco


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());
like image 14
lowerends Avatar answered Oct 22 '22 03:10

lowerends