首页 > 解决方案 > 在特定端口上使用 curl 调用 API

问题描述

我在端口 8000 下运行我的 Symfony。但 curl HTTP 在端口 80 上。

这意味着我的 curl 请求不起作用,因为我认为端口不好。

我试图指定要卷曲的端口。但是这样做会使呼叫请求失败......我没有错误消息,就像我尝试调用它时挂起一样。

我已经检查过这个问题:Unable to make php curl request with port number

我的 $url 就像http://127.0.0.1/app_dev.php/api/someapi

这里$result = $this->lib->CallAPI('POST', $url, $postfields);

在 Symfony 下运行以查找 URL,我应该有127.0.0.1:8000 但是我尝试在 URL 中设置端口,但没有为端口设置 curl 选项。我尝试使用不带端口的 URL,但为端口设置 curl 选项。它总是失败。

这是拨打电话的功能

function CallAPI($method, $url, $data = false)
{
    $curl = curl_init();

    switch ($method)
    {
        case "POST":
            curl_setopt($curl, CURLOPT_POST, 1);

            if ($data)
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_PUT, 1);
            break;
        default:
            if ($data)
                $url = sprintf("%s?%s", $url, http_build_query($data));
    }

    curl_setopt($curl,CURLOPT_PORT, 8000);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    $result = curl_exec($curl);

    curl_close($curl);

    return $result;
}

}

该行curl_setopt($curl,CURLOPT_PORT, 8000);似乎负责使我的请求处于待处理状态。

请注意,来自 Postman 的 API 调用是有效的,所以问题出在我用 curl 调用它的方式上。

谢谢你的帮助。

编辑:

我用了一个小技巧来看看出了什么问题。

我没有在 callApi() 中返回 $result,而是返回了 $curl。它在这个里面给我返回了一些 HTML

<h1 class="break-long-words exception-message">Whoops, looks like something went wrong.</h1>
<p class="break-long-words trace-message">An instance of Symfony\Bundle\FrameworkBundle\Templating\EngineInterface must be injected in FOS\RestBundle\View\ViewHandler to render templates.</p>

但是我不明白为什么定义 $curl 变量会产生这个错误,因为考虑到被调用的 API 正在邮递员上工作

EDIT2:事实上,这个错误是由于试图用 json_decode 转换 json 中的 curl 对象......所以没什么可做的。对不起。那时问题仍然存在。

标签: phpsymfonycurlfosrestbundle

解决方案


推荐阅读