百度雲中access token的生成代碼(c++版)

一、百度雲文字識別文檔中心
http://ai.baidu.com/docs#/Begin/top,先按其中的創建你需要的應用,產生後期需要應用的AK和SK,如圖所示
這裏寫圖片描述

二、3個依賴庫安裝
1、curl
2、json
3、openssl

三、Access token產生代碼

#include <iostream>
#include <curl/curl.h>
#include <json/json.h>
#include "access_token.h"

using namespace std;
const std::string access_token_url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials";
// 回調函數獲取到的access_token存放變量
// static std::string access_token_result;
/**
* curl發送http請求調用的回調函數,回調函數中對返回的json格式的body進行了解析,解析結果儲存在result中
* @param 參數定義見libcurl庫文檔
* @return 返回值定義見libcurl庫文檔
*/
static size_t callback(void *ptr, size_t size, size_t nmemb, void *stream) {
    // 獲取到的body存放在ptr中,先將其轉換爲string格式
    std::string s((char *)ptr, size * nmemb);
    // 開始獲取json中的access token項目
    Json::Reader reader;
    Json::Value root;
    // 使用boost庫解析json
    reader.parse(s, root);
    std::string* access_token_result = static_cast<std::string*>(stream);
    *access_token_result = root["access_token"].asString();
    return size * nmemb;
}

/**
* 用以獲取access_token的函數,使用時需要先在百度雲控制檯申請相應功能的應用,獲得對應的API Key和Secret Key
* @param access_token 獲取得到的access token,調用函數時需傳入該參數
* @param AK 應用的API key
* @param SK 應用的Secret key
* @return 返回0代表獲取access token成功,其他返回值代表獲取失敗
*/
int get_access_token(std::string &access_token, const std::string &AK, const std::string &SK) {
    CURL *curl;
    CURLcode result_code;
    int error_code = 0;
    curl = curl_easy_init();
    if (curl) {
        std::string url = access_token_url + "&client_id=" + AK + "&client_secret=" + SK;
        curl_easy_setopt(curl, CURLOPT_URL, url.data());
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
        std::string access_token_result;
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &access_token_result);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback);
        result_code = curl_easy_perform(curl);
        if (result_code != CURLE_OK) {
            fprintf(stderr, "curl_easy_perform() failed: %s\n",
                curl_easy_strerror(result_code));
            return 1;
        }
        access_token = access_token_result;
        curl_easy_cleanup(curl);
        error_code = 0;
    }
    else
    {
        fprintf(stderr, "curl_easy_init() failed.");
        error_code = 1;
    }
    return error_code;
}

void main()
{
    string access_token;
    get_access_token(access_token, "你的APIKey", "你的SecretKey");//第一個參數是記錄你申請的access token,第二個是API key ,第三個Secret key
    cout << access_token << endl;
    system("pause");
}

運行結果如圖所示:
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章