獲取access_token示例代碼


文檔中心--百度AI-百度AI開放平台 http://ai.baidu.com/docs#/NLP-API/top

#include <iostream>
#include <curl/curl.h>
#include <json/json.h>
#include "access_token.h"
// libcurl庫下載鏈接:https://curl.haxx.se/download.html
// jsoncpp庫下載鏈接:https://github.com/open-source-parsers/jsoncpp/
// 獲取access_token所需要的url
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;
}

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM