我在同一台服务器上有两个站点:
api.mysite.com john.mysite.com
在我的 API 站点上,我有一个接受 POSTed json 数组的服务。在我的 john.mysite.com 站点中,我正在调用该服务并使用以下方法发布它:
$info['id'] ="oo_".uniqid();
$info['version'] ="5";
$url = "http://api.mysite.com/services/addclient";
$posted_fields = json_encode($info);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
echo $result;
Run Code Online (Sandbox Code Playgroud)
当这被调用时,我没有收到任何发布到网络服务的信息。我已经进入该代码并转储 $_POST 并且它是空的。为什么 curl 不通过 POST 发送数据?
谢谢你的帮助!
一个问题是您正在json_encode输入数据而不是对其进行形式编码。
另一个是$info可能未初始化。
另一个是你$postfields在第 9 行打错了字。
尝试:
$info['id'] ="oo_".uniqid();
$info['version'] ="5";
$url = "http://api.mysite.com/services/addclient";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($info));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
echo $result;
Run Code Online (Sandbox Code Playgroud)