更新时间:2022-09-08 GMT+08:00
分享

PHP语言API示例

本示例以图像标签为例介绍如何使用PHP调用API。

<?php

function TokenRequest() {
    $url = "https://{endpoint}/v2/{project_id}/image/tagging";
    $token = "用户获取得到的实际token值";
    $imagePath = __DIR__.'data/image-tagging.jpg';

    $data = array();
    if (stripos($imagePath, 'http://') !== false || stripos($imagePath, 'https://') !== false) {
        $data['url'] = $imagePath;
    } else {
        if($fp = fopen($imagePath,"rb", 0))
        {
            $gambar = fread($fp,filesize($imagePath));
            fclose($fp);

            $fileBase64 = chunk_split(base64_encode($gambar));
        } else {
            echo "图片读取错误";
            return;
        }
        $data['image'] = $fileBase64;
    }

    $curl = curl_init();
    $headers = array(
        "Content-Type:application/json",
        "X-Auth-Token:" . $token
    );

    /* 设置请求体 */
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($curl, CURLOPT_NOBODY, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_TIMEOUT, 30);

    $response = curl_exec($curl);
    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);
    echo $response;
}

TokenRequest();
表1 参数说明

参数

参数说明

url

API请求URL,例如本示例中https://{endpoint}/v2/{project_id}/image/tagging。

token

Token是用户的访问令牌,承载了用户的身份、权限等信息,用户调用API接口时,需要使用Token进行鉴权。

获取Token方法请参见认证鉴权

imagePath

图片路径。支持图片文件路径或图片url路径。其中,图片的url路径支持公网http/https url或OBS提供的url。

分享:

    相关文档

    相关产品