oziks/restconnection

此包已被废弃且不再维护。未建议替代包。
此包的最新版本(1.0.0)没有可用的许可证信息。

用于轻松发送REST API请求的PHP类。

1.0.0 2013-10-15 13:09 UTC

This package is not auto-updated.

Last update: 2018-06-08 12:35:26 UTC


README

RESTConnection是一个PHP类,用于轻松地向REST API发送请求

关于

过程如下

  1. 实例化一个客户端对象,传递连接到您选择的REST API的通用参数。例如:服务的基础URL、凭证、头部(例如指定发送和接受的内容类型)

  2. 使用“request()”方法发送请求到该API,使用参数:URL路径、(可选)要发送的数据,以及要使用的方法(动词,例如:get、post、put...)

  3. 获取结果HTTP状态码、正文、头部、错误信息

虽然RESTConnection支持大多数使用的HTTP动词(get、post、put、delete、patch),但您可能处于只有get/post被支持的情况(您的防火墙可能阻止其他动词)。在这种情况下,您可以将兼容性模式设置为true。然后,每个delete、put、patch动词都将作为POST传递,并添加一个特殊的头部X-HTTP-Method-Override。另一方面,您可能还希望对特定请求强制执行此操作。以谷歌翻译为例,它通常将待翻译的单词作为GET。如果您要翻译整个段落,则必须将其作为POST传递,并强制X-HTTP-Method-Override为GET。您可以通过只需向请求参数列表中添加一个覆盖动词来轻松完成此操作。

示例

获取Twitter公开推文

// Initialize the header of our future requests, specifying the format we want to use in request and response (json)
$requestHeader = array('Accept: application/json', 'Content-Type: application/json');
// Create the Client object, for now, no credential needed as we get only public tweets
$testAPI = new RESTConnection\Client('https://api.twitter.com/1/', $requestHeader);

// Issue a GET request on 'https://api.twitter.com/1/statuses/public_timeline.json'
if($testAPI->request('statuses/public_timeline.json'))
{
  // Display the tweets
  var_dump(json_decode($testAPI->getResponseBody(), true));
}
else
{
  // Something went wrong
  var_dump($testAPI->getLastError());
}

向campfire发送消息,高亮显示它,然后更改房间主题

// Initialize the header of our future requests, specifying the format we want to use in request and response (json)
$requestHeader = array('Accept: application/json', 'Content-Type: application/json');
// Create the Client object, this time, credential are specified
$testAPI = new RESTConnection\Client('https://your.campfirenow.com/', $requestHeader, 'your_token_here', 'X');

// Issue a POST request on 'https://your.campfirenow.com/room/your_room_id/speak.json'
if($testAPI->request('room/your_room_id/speak.json', json_encode(array('message' => array('body' => "Hello"))), RESTConnection\Client::POST)))
{
  // lastStatusCode should be 201
  var_dump($testAPI->getLastStatusCode());
  // Response body contains the message id
  $result = (json_decode($testAPI->getResponseBody(), true));

  // star the message
  $messageid = $result['message']['id'];
  $testAPI->request(sprintf('messages/%s/star.json', $messageid), array(), RESTConnection\Client::POST);

  // unstar it
  // $testAPI->request(sprintf('messages/%s/star.json', $messageid), array(), RESTConnection\Client::DELETE);
}
else
{
  // Something went wrong
  var_dump($testAPI->getLastError());
}

// Issue a PUT request on 'https://your.campfirenow.com/room/your_room_id.json'
$testAPI->request('room/your_room_id.json', json_encode(array('room' => array('topic' => "this room is not about cats"))), RESTConnection\Client::PUT);

致谢

此代码部分基于以下文章: http://www.gen-x-design.com/archives/making-restful-requests-in-php/。感谢其作者。