【问题标题】:Differences in using PHP Curl vs command line curl使用 PHP Curl 与命令行 curl 的区别
【发布时间】:2013-02-19 09:44:18
【问题描述】:

我正在将 Badgeville REST API 与我的 PHP 5.3、curl 7.22 应用程序集成。

BV 的 API 文档都使用命令行 curl 调用作为示例。当我运行这些示例时,它们运行良好。

当我尝试对 PHP Curl 类做同样的事情时,我总是从 BV 服务器收到 500 错误。

我尝试使用 Chrome 中的 Advanced Rest Client 扩展来实现同义功能。

PHP 卷曲示例:

$ch = curl_init('http://sandbox.v2.badgeville.com/api/berlin/[private_api_key]/users.json');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);

if($this->getRequestType() == 'POST')
{
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, 
        array(
            'user[name]'    => 'Generic+Username',
            'user[email]'   => 'johndoe%40domainname.com'
        );
    );
}

$response   = curl_exec($ch);

休息客户端示例:

网址: http://sandbox.v2.badgeville.com/api/berlin/[private_api_key]/users.json

发布 没有标头有效负载:

user[name]=Generic+Username&user[email]=johndoe%40domainname.com

我已经手动创建了命令行 curl 调用并使用 shell_exec() 运行它,但我真的不想这样做。

在我的研究中,我发现了一个 Drupal module,所有 API 调用都是通过 fsockopen() 调用完成的。

有没有什么方法可以使用 PHP Curl 类成功地进行 Badgeville 调用?

【问题讨论】:

    标签: php api curl


    【解决方案1】:

    事实证明,当一个设置了标头的 curl 请求进入时,Badgeville 会出现 500 错误。

    错误返回码:

    $ch = curl_init('http://sandbox.v2.badgeville.com/api/berlin/[private_api_key]/users.json');
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
    
    if($this->getRequestType() == 'POST')
    {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, 
            array(
                'user[name]'    => 'Generic+Username',
                'user[email]'   => 'johndoe%40domainname.com'
            );
        );
    }
    
    $response   = curl_exec($ch);
    

    正常运行的代码:

    $ch = curl_init('http://sandbox.v2.badgeville.com/api/berlin/[private_api_key]/users.json');
    //curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
    
    if($this->getRequestType() == 'POST')
    {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, 
            array(
                'user[name]'    => 'Generic+Username',
                'user[email]'   => 'johndoe%40domainname.com'
            );
        );
    }
    
    $response   = curl_exec($ch);
    

    SMH

    【讨论】:

      猜你喜欢
      • 2013-04-18
      • 1970-01-01
      • 1970-01-01
      • 2017-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多