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 基于卷积神经网络的声纹识别
    • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
    • ¥100 为什么这个恒流源电路不能恒流?
    • ¥15 有偿求跨组件数据流路径图
    • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
    • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
    • ¥15 CSAPPattacklab
    • ¥15 一直显示正在等待HID—ISP
    • ¥15 Python turtle 画图
    • ¥15 stm32开发clion时遇到的编译问题