【问题标题】:Querying API through Curl/PHP通过 Curl/PHP 查询 API
【发布时间】:2013-08-04 06:38:44
【问题描述】:

我正在查看 Parse.com REST API 并使用 PHP 使用的 Curl 包装器进行调用。

原始卷曲代码(有效):

curl -X GET \
  -H "X-Parse-Application-Id: myApplicationID" \
  -H "X-Parse-REST-API-Key: myRestAPIKey" \
  https://api.parse.com/1/classes/Steps

PhP 代码(有效):

$ch = curl_init('https://api.parse.com/1/classes/Steps');

curl_setopt($ch,CURLOPT_HTTPHEADER,array('X-Parse-Application-Id: myApplicationID',
    'X-Parse-REST-API-Key: myRestAPIKey',
    'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_exec($ch);
curl_close($ch);

这很好,但现在当我尝试添加查询约束时:

原始卷曲代码(有效):

curl -X GET \
  -H "X-Parse-Application-Id: myApplicationID" \
  -H "X-Parse-REST-API-Key: myRestAPIKey" \
  -G \
--data-urlencode 'where={"steps":9243}' \
https://api.parse.com/1/classes/Steps

唉,我们最终得到了我的问题——上述代码的 php 模拟是什么?

PHP 代码(不起作用):

$ch = curl_init('https://api.parse.com/1/classes/Steps');

$query = urlencode('where={"steps":9243}');

curl_setopt($ch,CURLOPT_HTTPHEADER,array('X-Parse-Application-Id: myApplicationID',
    'X-Parse-REST-API-Key: myRestAPIKey',
    'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);

curl_exec($ch);
curl_close($ch);

错误响应:

Object ( [code] => 107 [error] => invalid json: where%3D%7B%22steps%22%3A9243%7D )

【问题讨论】:

    标签: php api curl parse-platform


    【解决方案1】:

    您的上一个 PHP 示例已将请求从 GET 更改为 POST。在查询字符串而不是 POST 正文中传递您的参数。试试:

    $query = urlencode('where={"steps":9243}');
    $ch = curl_init('https://api.parse.com/1/classes/Steps?'.$query);
    
    curl_setopt(
        $ch, 
        CURLOPT_HTTPHEADER,
        array(
            'X-Parse-Application-Id: myApplicationID',
            'X-Parse-REST-API-Key: myRestAPIKey',
            'Content-Type: application/json'
        )
    );
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
    curl_exec($ch);
    curl_close($ch);
    

    【讨论】:

    • 漂亮,谢谢!我对卷曲线 --data-urlencode 感到困惑(文档说它用于发布数据)。但是在查询中附加 url 确实有意义。
    • 关于 --data 参数是正确的,但是 -G 参数会强制它返回一个 GET。
    【解决方案2】:

    为了调用 GET,POST,DELETE,PUT 各种请求,我创建了一个通用函数

    define("SITEURL", "http://localhost:82/slimdemo/RESTAPI");
    
    function CallAPI($method, $api, $data, $headers) {
        $url = SITEURL . "/" . $api;
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    
        switch ($method) {
            case "GET":
                curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
                break;
            case "POST":
                curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
                break;
            case "PUT":
                curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
                break;
            case "DELETE":
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); 
                curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
                break;
        }
        $response = curl_exec($curl);
        $data = json_decode($response);
    
        /* Check for 404 (file not found). */
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        // Check the HTTP Status code
        switch ($httpCode) {
            case 200:
                $error_status = "200: Success";
                return ($data);
                break;
            case 404:
                $error_status = "404: API Not found";
                break;
            case 500:
                $error_status = "500: servers replied with an error.";
                break;
            case 502:
                $error_status = "502: servers may be down or being upgraded. Hopefully they'll be OK soon!";
                break;
            case 503:
                $error_status = "503: service unavailable. Hopefully they'll be OK soon!";
                break;
            default:
                $error_status = "Undocumented error: " . $httpCode . " : " . curl_error($curl);
                break;
        }
        curl_close($curl);
        echo $error_status;
        die;
    }
    

    调用 DeleteAPI

    $data = array('id'=>$_GET['did']);
    $header = array('USERTOKEN:' . GenerateToken());
    $result = CallAPI('DELETE', "DeleteCategory", $data, $header);
    

    调用 PostAPI

    $data = array('title'=>$_POST['txtcategory'],'description'=>$_POST['txtdesc']);
    $header = array('USERTOKEN:' . GenerateToken());
    $result = CallAPI('POST', "InsertCategory", $data, $header);
    

    调用 GetAPI

    $data = array('id'=>$_GET['eid']);
    $header = array('USERTOKEN:' . GenerateToken());
    $result = CallAPI('GET', "GetCategoryById", $data, $header);
    

    调用 PutAPI

    $data = array('id'=>$_REQUEST['eid'],m'title'=>$_REQUEST['txtcategory'],'description'=>$_REQUEST['txtdesc']);
    $header = array('USERTOKEN:' . GenerateToken());
    $result = CallAPI('POST', "UpdateCategory", $data, $header);
    

    【讨论】:

      【解决方案3】:

      这一行:

      curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
      

      正在尝试设置对 GET 请求无效的请求正文。 cURL 似乎允许您在 GET 请求 (example) 上设置正文。

      您的 PHP 似乎没有发出 POST 请求(至少我可以通过查看其他使用 curl_setopt($ch,CURLOPT_POST, count($fields)); 的 PHP 示例来判断。我相信您需要将数组传递给 postfields 选项:

      $fields = array(
          'where' => urlencode('{"steps":9243}')
      );
      
      curl_setopt($ch, CURLOPT_POST, count($fields));
      curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
      

      【讨论】:

      • 无耻插件:如果您使用 Runscope URL,您可以看到代码生成的 HTTP 请求/响应来回切换。
      【解决方案4】:

      试试这个:

      $query = json_encode(
          array(
              'where' => array( 'steps' => 9243 )
          )
      );
      

      我从here 收集到了这个——虽然没有测试! Python 示例在发送查询之前似乎对查询进行了 JSON 编码,因此可能值得尝试。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-22
        • 1970-01-01
        • 2018-09-08
        • 2017-07-09
        相关资源
        最近更新 更多