安装:
composer.json 添加 “guzzlehttp/guzzle”: “~6.0”,
然后执行:
composer update guzzlehttp/guzzle
完成安装
使用:
首先 use:
use GuzzleHttp\Client;
使用举例:
$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()或者 r e q u e s t − > a l l ( ) 或 者 _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都能获取到数据但是
r
e
q
u
e
s
t
−
>
a
l
l
(
)
或
者
p
h
p
:
/
/
i
n
p
u
t
都
能
获
取
到
数
据
但
是
_POST 获取不到数据
例如结果打印:
request->all() 的数据
array (
‘foo’ => ‘bar’,
)
$_POST 的数据
array (
)
file_get_contents(“php://input”)的数据:
{“foo”:”bar”}
获取请求的方法:
打印 $_SERVER[‘REQUEST_METHOD’] 即可
例如:
‘REQUEST_METHOD’ => ‘DELETE’,