yii2 restfulapi 的配置和访问
给user写相关接口
配置:修改UserController.php
use yii\rest\ActiveController;
use yii\helpers\ArrayHelper;
use yii\web\Response;
class UserController extends ActiveController
{
public $modelClass = 'backend\models\User';
}
curl访问接口:
1.get
//id>0为获取单个用户的信息
$id = "";
if(isset($_GET['id'])){
$id = $_GET['id'];
}
$ch = curl_init("http://my.qiji.com/user/".$id) ;
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ;
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ;
curl_setopt($ch, CURLOPT_HEADER, true );
//$aHeader[] = "Accept:application/xml";
$aHeader[] = "Accept:application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
$output = curl_exec($ch) ;
print_r($output);
2.post创建一个信息用户
$ch = curl_init("http://my.qiji.com/user/create") ;
$post_data = array ("company_name" => "bob","company_profile" => "12345");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ;
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ;
curl_setopt($ch, CURLOPT_HEADER, true );
//$aHeader[] = "Accept:application/xml";
$aHeader[] = "Accept:application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch) ;
print_r($output);
3.put修改用户信息
$ch = curl_init("http://my.qiji.com/user/update/30") ;
$post_data = array ("company_name"=> 30,"company_name" => "bob","company_profile" => "12345");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ;
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ;
curl_setopt($ch, CURLOPT_HEADER, true );
//$aHeader[] = "Accept:application/xml";
$aHeader[] = "Accept:application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT' );
$output = curl_exec($ch) ;
print_r($output);
4delete删除一个用户
$id = "";
if(isset($_GET['id'])){
$id = $_GET['id'];
}
$ch = curl_init("http://my.qiji.com/user/delete/".$id) ;
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ;
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ;
curl_setopt($ch, CURLOPT_HEADER, true );
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE' );
$aHeader[] = "Accept:application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
$output = curl_exec($ch) ;
print_r(json_decode($output));