C++ cURL JSON将标记保存到文件或cookie

nwsw7zdq  于 2022-12-15  发布在  其他
关注(0)|答案(2)|浏览(140)

我想将令牌从oAUTH2登录保存到文件或cookie,但当我尝试将其保存到文件时,我收到来自cURL的消息:response when I try to save data to memory但是当我注解这一行时:

curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);

然后控制台显示来自服务器的带有令牌的正常JSON响应
下面是我的代码:

chunk.memory = (char*)malloc(1);  /* will be grown as needed by the realloc above */
chunk.size = 0;    /* no data at this point */
CURL *curl;
CURLcode res;
char* curlErrStr = (char*)malloc(CURL_ERROR_SIZE);
curl = curl_easy_init();
curl_slist* httpHeaders = NULL;
if(curl) 
{
struct curl_slist* headers = NULL;

curl_slist_append(headers, "HOST: xxx");
curl_slist_append(headers, "Content-Type: application/json");   
curl_slist_append(headers, "Accept: application/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0");
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl, CURLOPT_URL, "xx");
/* Now specify the POST data */
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "username=xxx&password=xxx");

/* get it! */

res = curl_easy_perform(curl);

/* check for errors */
if (res != CURLE_OK) {
    fprintf(stderr, "curl_easy_perform() failed: %s\n",
        curl_easy_strerror(res));
}
else {

    printf("%lu bytes retrieved\n", (long)chunk.size);
}
    
ofstream oplik;
oplik.open("get_token.json");
oplik << chunk.memory;
oplik.close();
curl_easy_cleanup(curl);
if (chunk.memory)
    free(chunk.memory);
curl_global_cleanup();

所以我想还是保存库奇吧,对吧?
也许一些样本代码如何保存到cookie?

s4chpxco

s4chpxco1#

只要添加这段代码,它就可以工作了:)非常感谢Alan Birtles

curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
0lvr5msh

0lvr5msh2#

curl -X POST https://reqbin.com/echo/post/json
   -H 'Content-Type: application/json'
   -d '{"login":"my_login","password":"my_password"}'

相关问题