php - 在特定端口上使用 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 对象......所以没什么可做的。对不起。那时问题仍然存在。
解决方案
推荐阅读
- api - 如何将我的地图对象数据转换为列表?
- sql - 如果 Teradata 的表中不存在记录,如何将新记录插入表中
- android - 如何使用 ConstraintLayout 在 Android 中针对不同屏幕尺寸缩放 UI 元素
- mysql - 通过将单个消息发布到 kafka 来更新 mysql 中的多个字段
- java - http服务器是否在verticle上运行并拥有自己的事件循环?
- python - 我想反转以下代码的输出格式(行和行号都应该是相反的顺序)
- git - 推送新创建的分支时,远程主机错误消息关闭与 gitlab 的连接
- java - 带有配置文件的 gradle 构建文件名
- php - 如何使用 query() 函数从多个表中实现 Laravel 查询?
- flutter - 在颤动中保持所有变量和函数私有是一种好习惯吗?