doulai8128 2017-09-05 12:30
浏览 80

如何在laravel 5.4中调用REST API

I have developed a laravel project in which I want to call a REST API to pass a form inputs to it by the use of CURL. After submitting a form by user, form data are passed to a controller, then API is called but I receives false or null as response. The data must be sent to API as below, as you see the data must be a json in an array(image is not a file, it is a path):

[{
    'title' : 'title',
    'body' : 'description',
    'source' :  'http://www.google.com',
    'date' : 1503845107465,
    'active' : true,
    'image' : '758.jpg',
    'category' : [
        1
    ]
}];

here is a part of my controller, $data is build out of form inputs.

$data = [
       'title' => 'title',
       'body' => 'description',
       'source' =>  'http://www.google.com',
       'date' => 1503845107465,
       'active' => true,
       'image' => '758.jpg',
       'category' => [
        1
        ]
    ];
        $curl=curl_init('http://x.x.x.x/rest/test');

        $send = json_encode([$data]);
        //return $send;
        //curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($curl, CURLOPT_POSTFIELDS, $send);

        try{
            $res = curl_exec($curl);
        }catch (Exception $e){
            return $e->getMessage();
        }

        dd($res);

$res is false. It must be mentioned that the code in controller works on localhost but it does not work on linux server.

I also used ixudra/curl but it does not solve my problem and it returns null.

I got this error Failed to connect to x.x.x.x Permission denied. I can ping this url and I can send data with curl to this IP in a php file. but in laravel I get this error

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
    • ¥15 画两个图 python或R
    • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
    • ¥15 八路抢答器设计出现故障
    • ¥15 请教一下c语言的代码里有一个地方不懂
    • ¥15 opencv 无法读取视频
    • ¥15 用matlab 实现通信仿真
    • ¥15 按键修改电子时钟,C51单片机
    • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
    • ¥20 5037端口被adb自己占了