跟外界产品合做对接API的时候,不少时候要求post方式传递json格式的数据。下面简单讲讲处理方式。php
传递json格式数据的时候,须要注意:json
使用Postman演示api
使用php代码演示app
说明:
本实例依赖composer Guzzle扩展composer
composer require guzzlehttp/guzzle
具体代码:ide
/** * 发送api请求 * @param string $api api地址 * @param array $postData 传递的数据 * @return mixed|string */ function sendApiRequest(string $api,array $postData) { $client = new \GuzzleHttp\Client([ 'headers' => [ 'Content-Type' => 'application/json' ] ]); $response = $client->request('POST',$api,['body' => json_encode($postData),]); $result=$response->getBody()->getContents(); $result = \GuzzleHttp\json_decode($result,true); return $result; }