我正在尝试将 JSON 编码的 HTTP POST 数据发送到远程服务器。
使用 cURL,这将完成
curl -X POST -H "Content-Type: application/json" -d '{"name":"Jeff"}' http://somesite/someuri
我找不到 Laravel 方法来执行此操作。
[ * * * 更新:我的解决方案 * * * ]
我最终使用了 PHP 的 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();
最佳答案
在 this SO post我回答了一个非常相似的问题,它可以直接解决您的问题,请点击链接获取详细说明。
如何在 Laravel 4 中通过 CURL (jyggen/curl) 通过 POST 发送 JSON
简而言之,安装jyggen/curl package后在带有 Composer 的 Laravel 应用程序中,您所要做的就是:
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());
}
关于json - 如何在 Laravel 4 中将 JSON 数据 POST 到远程服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17702008/