如何使用laravel 5.6中的CURL中的post方法调用REST-API?

时间:2018-05-16 20:47:44

标签: php laravel rest php-curl

我正在使用laravel 5.6.I想用发布方法调用 REST-API 。其中URL参数为 JSON格式。我只是在 Postman 中调用该API。它正在工作。但是当我尝试通过 CURL 方法调用 Laravel控制器时, 错误

Array to string conversion

JSON参数是

{"DebtorID":"00000000080000000002","InitiatedDate":"2018-04- 
 20","OrderNo":"1234","SOReference":"Test order",  
 "Lines":[{"PartNo":"1170","QuantityOrdered":5}, 
          {"CommentLine":"true","CommentText":"This is a comment line"},
          {"InventoryID":"000000000K00000000BV","QuantityOrdered":2,  
           "DiscountedPrice":15.67,
            "CustomFieldValues":[
              {SettingID":"1ae102b94dc54dfc8a45",
                "Contents":"Fragile - do not drop"
                   }
                ]
            }
          ],
           "Payments":[{"PaymentRef":"S454873-J5","AmountPaid":50.00}]
        }
}

我的Laravel代码

        $curl = curl_init();
        curl_setopt_array($curl, array(
        CURLOPT_URL =>$request->url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER=>false,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30000,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => $request->data,
        CURLOPT_HTTPHEADER => array(
            // Set here requred headers
            "accept: */*",
            "accept-language: en-US,en;q=0.8",
            "content-type: application/json",
            "Accept: application/json",
        ),
    ));
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);

这是从Postman调用的示例图像。当我直接调用此API时,它返回200。 enter image description here

但是当我从laravel尝试这个然后得到错误。请检查此图片。 enter image description here

我尝试使用 postman Generate code Snippets ,图片位于下方 enter image description here

1 个答案:

答案 0 :(得分:0)

只需使用内容类型检查响应格式,以便能够以正确的格式打印。

 $contentType = curl_getinfo($curl, CURLINFO_CONTENT_TYPE);
    echo $contentType;
    echo "<br/>";
  curl_close ($curl);
    echo "<pre>";