3)使用REST Client类库访问
第三种方法是可以使用开源的REST Client类库(http://github.com/philsturgeon/codeigniter-restclient)去访问REST,比如同样上面的代码,可以写成:
function rest_client_example($id)
{
$this->load->library("rest", array(
"server" => "http://localhost/restserver/index.php/example_api/",
"http_user" => "admin",
"http_pass" => "1234",
"http_auth" => "basic" // 或者使用"digest"
));
$user = $this->rest->get("user", array("id" => $id), "json");
echo $user->name;
}
看,是不是更简单了!这里是示例说明了调用GET方法,并且说明返回的形式是JSON的,当然你也可以指定其他形式的返回结果,比如xml,php,csv等,比如:
$user = $this->rest->get("user", array("id" => $id), "application/json");
同理,可以使用$this->rest->post(),$this->rest->put(),$this->rest->delete()等。
最后,我们学习下如何跟twitter的RESTful API打交道,使用RESTful Client library,只需要如下这样的编写简单代码即可:
$this->load->library("rest", array("server" => "http://twitter.com/"));
$user = $this->rest->get("users/show", array("screen_name" => "philsturgeon"));这个是调用twitter的RESTful API去获得某个用户ID的资料,
$this->load->library("rest", array(
"server" => "http://twitter.com/",
"http_user" => "username",
"http_pass" => "password",
"http_auth" => "basic"
));
$user = $this->rest->post("statuses/update.json", array("status" => "Using the REST client to do stuff"));
这个代码段则是更新某个用户的状态。

