【问题标题】:Convert Terminal cURL to PHP cURL Script将终端 cURL 转换为 PHP cURL 脚本
【发布时间】: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);
  • 我已经用不同的解决方案修复了它,无论如何,谢谢。
  • 解决方案是什么?

标签: php curl


【解决方案1】:

复制您的终端 curl 脚本并将其导入 Postman。然后从导出选项将其转换为 PHP CURL。无需手动转换。

参考 -

  1. https://www.getpostman.com/docs/importing_curl
  2. How to export specific request to file using postman

【讨论】:

  • 我在尝试导入 cURL 时总是收到此错误。 Error while importing Curl: Zero or Multiple option-less arguments. Only one is supported (the URL)
【解决方案2】:

将此行添加到 cURL 后它起作用了:

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=UTF-8'));

【讨论】:

    猜你喜欢
    • 2016-03-20
    • 2014-04-12
    • 2021-10-24
    • 2016-03-07
    • 2017-06-05
    • 1970-01-01
    • 2017-08-03
    • 2019-06-04
    • 2017-12-03
    相关资源
    最近更新 更多