实验环境:
- IDE:Eclipse for PHP Developers
- Version: Neon.1 Release (4.6.1)
- Server:WampServer Version 2.5
- HttpClient:guzzle
1. 使用composer安装Guzzle
-
composer.json文件
{ "require": { "guzzlehttp/guzzle": "~6.0" } }
-
composer.phar下载
-
打开控制台指令,在项目目录下运行如下指令完成包的安装
php composer.phar install
2. 证书安装
注意:默认的http客户端工具一般到需要证书的认证,如果没有导入相应的证书一般会报SSL证书认证错误。
-
下载证书到本地,下载地址,将其保存到相应的位置。
-
为了让证书生效需要相应修改php.ini,修改方法如下:
curl.cainfo =<filepath>/cacert.pem
3. PHP代码示例
1<?php 2use GuzzleHttp\Psr7\Request; 3use GuzzleHttp\Client; 4 5require_once 'vendor\autoload.php'; 6 7$client = new Client(); 8 9$headers = ['Content-Type' => 'application/json','Ocp-Apim-Subscription-Key' => '{key}']; 10$body = '{"url":"{image's url}"}'; 11 12$request = new Request('POST','https://api.cognitive.azure.cn/face/v1.0/detect', $headers , $body); 13 14$response = $client->send($request); 15 16echo $response->getBody(); 17?>
4. 运行结果示例
1[{"faceId":"b22efa8f-0e34-4344-8346-ca8b79d29a27","faceRectangle":{"top":181,"left":184,"width":257,"height":257}}] 2 3
5. 读取本地图片
1<?php 2 3use GuzzleHttp\Psr7\Request; 4use GuzzleHttp\Client; 5 6require_once 'vendor\autoload.php'; 7 8$client = new Client(); 9 10$headers = ['Content-Type' => 'application/octet-stream','Ocp-Apim-Subscription-Key' => 'bd8e4ce12f444c639ac9c214d70ac72c']; 11 12$myfile = fopen("tt.jpg", "r") or die("Unable to open file!"); 13 14$request = new Request('POST','https://api.cognitive.azure.cn/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=age', $headers , $myfile); 15 16$response = $client->send($request); 17 18echo $response->getBody(); 19 20fclose($myfile); 21?>
6. 更多参考
- 关于key的获取可以登录世纪互联官方网站申请账户,在新版本的 portal 中即可创建认知服务。
- 认知服务RestAPI参考