首页 > 解决方案 > 在 PHP 中向 API 发送数据

问题描述

选项1:

$data= array(
    "Code" => "abcde",
    "Id" => "A007",
    "RefNo" => "123456",
    "UserName" => "QWE",
    "UserEmail" => "qwe@gmail.com",
);
$url="https://testing.php";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result=curl_exec($ch);
curl_close ($ch);
echo $result;
}


选项 2:

<form method="post" action="https://testing.php">
    <input type="hidden" value="abcde" name="Code">
    <input type="hidden" value="A007" name="Id">
    <input type="hidden" value="QWE" name="UserName">
    <input type="hidden" value="qwe@gmail.com" name="UserEmail">
    <input type="hidden" value="123456" name="RefNo">
    <input type="submit" name="submit">
</form>


A和B有什么不同吗?因为我两者都试过了,但 curl 只能从 api 得到“失败”响应。

标签: phpcurl

解决方案


没有区别,因为它们都发送 POST 请求,但您可以说您使用的技术的唯一区别:

  • 第一个可以完全从后端完成,它允许您在将数据发送到 API 之前对其进行验证。
  • 其次不允许这样的事情,您可能必须在提交之前编写javascript代码进行验证。

您将面临的错误可能是由于您的请求中缺少数据。或者您的 IP 地址未在您尝试访问其 API 的服务器上列入白名单。

此外,没有这样的 URL,https://testing.php,请尝试使用您的 IP 地址或完整的服务器地址来发送请求。


推荐阅读