【发布时间】:2016-11-12 21:55:17
【问题描述】:
我正在尝试将以下值发布到 API 中,并取回响应,它在使用 curl 命令的终端上运行良好,但在我使用 MAMP 在 localhost 上运行的 PHP 文件上却没有。
{"userCode":"user478","imei":"39BB4E91-71E8-468D-9FDE-AA2222A93F04","deviceModel":"iPhone5,3","email":"example@mail.com"}
这是我的 PHP 代码不起作用:
function doRequest($method, $url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, false);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip', 'deflate');
curl_setopt($ch, CURLOPT_USERAGENT, "CarteiraPagamento/1.0.3 (iPhone; iOS 9.3.2; Scale/2.00)");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, getcwd().'/cookies/out.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, getcwd().'/cookies/out.txt');
curl_setopt($ch, CURLOPT_REFERER, 'https://example.com/');
curl_setopt($ch, CURLOPT_VERBOSE, 1);
if ($method == 'POST') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"userCode":"user478","imei":"39BB4E91-71E8-468D-9FDE-AA2222A93F04","deviceModel":"iPhone5,3","email":"example@mail.com"}');
}
当我在终端上运行 curl 命令时,我得到了正确的响应。
curl -i -s -k -X 'POST' \
-H 'Content-Type: application/json; charset=utf-8' -H 'User-Agent: CarteiraPagamento/1.0.3 (iPhone; iOS 9.3.2; Scale/2.00)' \
--data-binary $'{\"userCode\":\"user478\",\"imei\":\"39BB4E91-71E8-468D-9FDE-AA2222A93F04\",\"deviceModel\":\"iPhone5,3\",\"email\":\"example@mail.com\"}' \
'https://ws.example.com/example'
如何将此命令转换为使用 PHP curl?
【问题讨论】:
-
这两种方法的输出有什么区别?
-
当我尝试使用 PHP 脚本时,我得到:
{"errorCode":"1000","message":"Request can not be completed. Please try again later."}但是当我在终端上尝试使用 curl 命令时,我得到了正确的响应,以及我想要的数据。 -
尝试添加
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); -
我已经用不同的解决方案修复了它,无论如何,谢谢。
-
解决方案是什么?