JSON requests in C using libcurl

前端 未结 7 876
孤独总比滥情好
孤独总比滥情好 2020-12-08 12:04

I\'m defining a PUT request with a JSON request body using libcurl in C.

This how I\'m doing it:

    sprintf(jsonObj, \"\\\"name\\\" : \\\"%s\\\", \\         


        
相关标签:
7条回答
  • 2020-12-08 12:53

    I was having a similar Issue.

    I discovered the -libcurl option for the curl command. It helped a lot! Just add it to the end of your working curl command.

    In the end it help me create this code:

      CURLcode ret;
      CURL *hnd;
      struct curl_slist *slist1;
      std::string jsonstr = "{\"username\":\"bob\",\"password\":\"12345\"}";
    
      slist1 = NULL;
      slist1 = curl_slist_append(slist1, "Content-Type: application/json");
    
      hnd = curl_easy_init();
      curl_easy_setopt(hnd, CURLOPT_URL, "http://u/r/l");
      curl_easy_setopt(hnd, CURLOPT_NOPROGRESS, 1L);
      curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, jsonstr.c_str());
      curl_easy_setopt(hnd, CURLOPT_USERAGENT, "curl/7.38.0");
      curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, slist1);
      curl_easy_setopt(hnd, CURLOPT_MAXREDIRS, 50L);
      curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST");
      curl_easy_setopt(hnd, CURLOPT_TCP_KEEPALIVE, 1L);
    
      ret = curl_easy_perform(hnd);
    
      curl_easy_cleanup(hnd);
      hnd = NULL;
      curl_slist_free_all(slist1);
      slist1 = NULL;
    

    Express recieves this JSON as:

    { username: 'bob', password: '12345' }
    

    I hope this helps!

    0 讨论(0)
提交回复
热议问题