代码拉取完成,页面将自动刷新
#include <stdio.h>
#include <stdlib.h>
#include <string.h> //strdup
#include <cjson/cJSON.h>
#include "http.h"
#include "auth.h"
char* get_token(const char* ak, const char* sk)
{
char* token = NULL;
//设置URL
char* url = "https://aip.baidubce.com/oauth/2.0/token";
char* form = NULL;
asprintf(&form, "grant_type=client_credentials&client_id=%s&client_secret=%s&", ak, sk);
//发送请求报文
size_t size = strlen(form);
char* response = post(url, NULL, form, &size);
free(form);
if (!response)
{
return NULL;
}
//解析响应报文
cJSON* root = cJSON_ParseWithLength(response, size);
free(response);
if (!root)
{
const char *error_ptr = cJSON_GetErrorPtr();
if (error_ptr != NULL)
{
fprintf(stderr, "Error before: %s\n", error_ptr);
}
return NULL;
}
cJSON* access_token = cJSON_GetObjectItem(root, "access_token");
if (!access_token)
{
fprintf(stderr, "access_token attribute not found\n");
cJSON_Delete(root);
return NULL;
}
if (!cJSON_IsString(access_token))
{
fprintf(stderr, "access_token attribute format error\n");
cJSON_Delete(root);
return NULL;
}
token = strdup(access_token->valuestring);
// 删除解析后对象占用的内存
cJSON_Delete(root);
return token;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。