2

I am trying to HTTP POST JSON encoded data to a remote server.

Using cURL, this would be done as

curl -X POST -H "Content-Type: application/json" -d '{"name":"Jeff"}' http://somesite/someuri

I can not find a Laravel approach to doing this.

[ * * * UPDATE: My Solution * * * ]

I ended up using PHP's HttpRequest

$httpRequest_OBJ = new httpRequest($server, HTTP_METH_POST, NULL);
$httpRequest_OBJ->setBody($jsonEncodedData);
$httpRequest_OBJ->setContentType('application/json');
$result = $httpRequest_OBJ->send();
$reply = $result->getBody();
3

2 Answers 2

2

In this SO post I answered a very similar question, and it's a direct solution to your problem, please follow the link for detailed instructions.

How to send JSON by POST in Laravel 4 via CURL (jyggen/curl)
To put it in a nutshell, after you install the jyggen/curl package in your laravel app with composer, all you have to do is:

use jyggen\Curl;
$url = "http://some.url/"; //the gateway to which you want to post the json payload
$file = 'path/to/file.json';
$data = File::get($file); //or wherever else you get your json from

$request = new Request($url); // jyggen\Curl\Request

$request->setOption(CURLOPT_FOLLOWLOCATION, true);
$request->setOption(CURLOPT_RETURNTRANSFER, true);

$request->setOption(CURLOPT_POST, true);
$request->setOption(CURLOPT_POSTFIELDS, $data);

$request->setOption(CURLOPT_HTTPHEADER, array(                                                                          
'Content-Type: application/json',
);

$request->execute();

if ($request->isSuccessful()) {
    return $request->getRawResponse();
} else {
    throw new Exception($resquest->getErrorMessage());
} 
0
0

Above @Gadoma example works pretty well in Laravel 5 also. But I had to change use to:

use Jyggen\Curl\Request;   

and also remove line:

$request->setOption(CURLOPT_RETURNTRANSFER, true);

since there were some errors. Now it works like charm.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.