lumen5:在Controller.php中封装http请求
*使用依赖包guzzlehttp/guzzle即可
1。首先安装
2。使用这个包
use GuzzleHttp;
3。写方法使用
public function request($method, $url, array $options = [])
{
$client = new GuzzleHttp\Client();
$res = $client->request($method, $url, $options);
$body = $res->getBody()->getContents();
$data = json_decode($body);
return $data;
}
4。调用的时候
public function getAllUser($token)
{
/*get*/
$data = $this->request('GET', 'https://oapi.dingtalk.com/user/get_org_user_count?access_token=' . $token . '&onlyActive=1');
/*post*/
$data = $this->request('POST', $this->ADMIN_URL . '/api/v1/signed_user_list', ['json' => $req]);
return $data;
}
5.具体的使用举例子
$client = new Client();
try {
$response = $client->request('PUT',$url,[
'body' => json_encode(['foo' => 'bar'])
]
);
Log::info('返回');
$statusCode = $response->getStatusCode();
$rsp = $response->getBody()->getContents();
//$arrRes = json_decode($rsp, true);
Log::info($statusCode);
Log::info($rsp);
} catch (\Exception $e) {
echo 'error: ';
echo $e->getMessage();
}
try catch 获取错误
put 的url 使用如下方式获取 body 数据:
$rsp = file_get_contents("php://input");
提交 form 表单:
$response = $client->request('POST',$url,[
'form_params' => [
'accountId' => $accountId,
'orderId' => $orderId,
'mac' => $mac
]
那么 request−>all()或者_POST 即可获取值
注意:
Laravel 或者其他框架一般会开启 CSRF验证,这么提交是不会通过验证的,可能会返回500 这个时候 被请求方应该 关闭这个验证
1.laravel 可以直接注释掉这个中间\App\Http\Middleware\VerifyCsrfToken::class,
2.laravel 在这个中间件里面添加排除路由
3.laravel 使用 api 接口
请求数据 json格式:
$response = $client->request('POST',$url,[
'json' => ['foo' => 'bar']
]
此时请求方 request−>all()或者php://input都能获取到数据但是_POST 获取不到数据
例如结果打印:
request->all() 的数据
array (
‘foo’ => ‘bar’,
)
$_POST 的数据
array (
)
file_get_contents(“php://input”)的数据:
{“foo”:”bar”}
获取请求的方法:
打印 $_SERVER[‘REQUEST_METHOD’] 即可
例如
‘REQUEST_METHOD’ => ‘DELETE’,