REST API实现示例代码

时间:2011-03-21 05:53:37

标签: php json rest

我对实现API一无所知。我知道PHP了。我有一种情况需要调用REST API方法来清除CDN服务器上的缓存。有人可以帮我提供一些示例代码吗?

以下是样本请求:

PUT <<url>>
Authorization: TOK:12345-12345
Accept: application/json
Content-Type: application/json
Host: api.edgecast.com
Content-Length: 87
{
   "MediaPath":"<<urlhere>>"
   "MediaType":"3"
}

有人可以帮助我使用代码来实现这个rest api请求吗? 提前谢谢。

3 个答案:

答案 0 :(得分:2)

我也必须找到困难的方法。这已经过测试(我的原始代码稍作修改)

//## GoGrid PHP REST API Call

define('TOKEN','XXXXX-XXXXX-XXXXX-XXXXXX');     // found on the cdn admin My Settings
define('ACCOUNT_NUMBER','XXXX');        // found on the cdn admin Top Right corner

function purgeCacheFileFromCDN($urlToPurge) {
  //## Build the request
  $request_params = (object) array('MediaPath' =>  $urlToPurge, 'MediaType' => 8);   // MediaType 8=small 3=large
  $data = json_encode($request_params);

  //## setup the connection and call.
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, 'https://api.edgecast.com/v2/mcc/customers/'.ACCOUNT_NUMBER.'/edge/purge');
  curl_setopt($ch, CURLOPT_PORT , 443);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLINFO_HEADER_OUT, 1);                  // For debugging
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);             // no caching  
  curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);            // no caching  
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
  curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: tok:'.TOKEN, 'Content-Type: application/json','Accept: application/json', 'Content-length: '.strlen($data)));
  $head = curl_exec($ch);
  $httpCode = curl_getinfo($ch);
  curl_close($ch);

  //## check if error
  if ($httpCode['http_code'] != 200) {
    echo 'Error reported: '.print_r(array($head,$httpCode),1);  // output it to stdout this will be emailed to me via cron capture.
  }
}

答案 1 :(得分:1)

从头开始编写的内容太懒了,所以从谷歌在结果的第一页建议的 amazingly pink 网站上复制。

    $data = array("a" => $a);
    $ch = curl_init($this->_serviceUrl . $id);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
    curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));

    $response = curl_exec($ch);
    if(!$response) {
        return false;
    }

PS:源搜索请求:http://www.google.ru/search?q=php+sample+put+request+curl

答案 2 :(得分:0)

对于考虑使用EdgeCast API的其他人来说,

Here是我完全实现的Grunt任务的源头要点。您将在我的示例中找到我使用节点模块执行清除CDN的curl命令。

这是我花了好几个小时试图让HTTP请求在Node中工作后结束的。我能够使用Ruby和Python工作,但不符合这个项目的要求。