【问题标题】:How can I POST JSON data to a remote server in Laravel 4?如何在 Laravel 4 中将 JSON 数据发布到远程服务器?
【发布时间】:2013-07-16 03:17:29
【问题描述】:

我正在尝试将 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();

【问题讨论】:

标签: json forms post laravel


【解决方案1】:

this SO post我回答了一个非常相似的问题,直接解决了你的问题,详细说明请点击链接。

如何通过 CURL (jyggen/curl) 在 Laravel 4 中通过 POST 发送 JSON
简而言之,在你使用 composer 在你的 laravel 应用中安装 jyggen/curl package 之后,你所要做的就是:

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());
} 

【讨论】:

    【解决方案2】:

    @Gadoma 上面的例子在 Laravel 5 中也很有效。但我不得不改变使用:

    use Jyggen\Curl\Request;   
    

    还有删除行:

    $request->setOption(CURLOPT_RETURNTRANSFER, true);
    

    因为有一些错误。现在它就像魅力一样发挥作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多