1 Star 0 Fork 1

梦落雨深/自动作诗

forked from 刘煜/自动作诗 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
poet.c 2.54 KB
一键复制 编辑 原始数据 按行查看 历史
刘煜 提交于 2019-11-25 09:57 . first commit
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include "cJSON.h"
#define APPID "17846293"
#define APPKEY "5OGpgFrroMaief5aTNQGMQPD"
#define SECRETKEY "0PxiO567mTTfQBPv1PQPsTzBOCAUA08j"
CURL *curl;
char *get_token(const char *appkey, const char *secretkey)
{
char *request;
char *response;
size_t resplen;
asprintf(&request, "grant_type=client_credentials&client_id=%s&client_secret=%s", appkey, secretkey);
FILE *fp = open_memstream(&response, &resplen);
if (!fp)
perror("open_memstream");
curl_easy_setopt(curl, CURLOPT_URL, "http://openapi.baidu.com/oauth/2.0/token");
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, request);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK)
puts(curl_easy_strerror(res));
fclose(fp);
cJSON *resp = cJSON_Parse(response);
//puts(cJSON_Print(resp));
cJSON *token = cJSON_GetObjectItemCaseSensitive(resp, "access_token");
char *retval = strdup(token->valuestring);
free(response);
cJSON_Delete(resp);
return retval;
}
int poet_init()
{
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
return 0;
}
void poet_cleanup()
{
curl_easy_cleanup(curl);
curl_global_cleanup();
}
void make_poem(char *input)
{
char * url;
char *request;
char *response;
size_t resplen;
struct curl_slist *header = NULL;
char* token = get_token(APPKEY, SECRETKEY);
asprintf(&url, "https://aip.baidubce.com/rpc/2.0/creation/v1/poem?access_token=%s", token);
free(token);
asprintf(&request, "{\"text\": \"%s\", \"index\": 0}", input);
puts(request);
FILE *fp = open_memstream(&response, &resplen);
if (!fp)
perror("open_memstream");
curl_easy_setopt(curl, CURLOPT_URL, url);
header = curl_slist_append(header, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, request);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK)
puts(curl_easy_strerror(res));
fclose(fp);
cJSON *resp = cJSON_Parse(response);
puts(cJSON_Print(resp));
cJSON *poem = cJSON_GetObjectItemCaseSensitive(resp, "poem");
cJSON *obj;
cJSON_ArrayForEach(obj, poem)
{
cJSON *title = cJSON_GetObjectItemCaseSensitive(obj, "title");
cJSON *content = cJSON_GetObjectItemCaseSensitive(obj, "content");
printf("%s\n", title->valuestring);
printf("%s\n", content->valuestring);
}
free(response);
cJSON_Delete(resp);
}
int main(int argc, char** argv)
{
poet_init();
make_poem(argv[1]);
poet_cleanup();
return 0;
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C
1
https://gitee.com/deep_dream/poet_robot.git
git@gitee.com:deep_dream/poet_robot.git
deep_dream
poet_robot
自动作诗
master

搜索帮助