Home > Software engineering >  C cURL JSON save token to file or cookie
C cURL JSON save token to file or cookie

Time:12-09

i want to save token from oAUTH2 login to file or cookie, but when i try to save it to file i get msg from cURL : response when i try to save data to memory but when i comment line

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

Then console shows me normal JSON response from server with token

my code:

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();

So i think i should save it to cookie, am i right ?

maybe some sample code how to save it to cookie?

CodePudding user response:

Just add this code and it works :) big thanks to Alan Birtles

curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);

CodePudding user response:

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