使用curl和json-c从C调用json webservice

Kir*_*jja -1 c json curl web-services

我需要调用一个接受json对象的宁静的Web服务。我能够找到像libcurl这样的库来从C应用程序调用Web服务。我还能够找到像json-c这样的库来在C中创建一个json对象。

libcurl接受一个字符串并将其发布到给定的Web服务URL。无论如何,我可以发布使用json-c库创建的json对象,并使用curl库调用Web服务。

请让我知道是否有其他库可以同时允许我创建一个json对象并调用Web服务或任何其他替代解决方案。

谢谢您的帮助。

jyv*_*vet 5

这是使用两个库的示例:

#include <stdio.h>
#include <curl/curl.h>
#include <json-c/json.h>

int  main(int argc, char **argv)
{

  /* LIB JSON-C PART */
    /* Create a JSON object */
    json_object * jObj = json_object_new_object();

    /* Create a string element */
    json_object *jString = json_object_new_string("Guybrush");

    /* Include the element to the JSON final object */
    json_object_object_add(jObj,"name", jString);


  /* LIB CURL PART */
    /* Initialize CURL */ 
    CURL *curlHandler = curl_easy_init();

    if(curlHandler) {
      /* Set CURL parameters */
      curl_easy_setopt(curlHandler, CURLOPT_URL, "http://api.yoururl.com");
      curl_easy_setopt(curlHandler, CURLOPT_CUSTOMREQUEST, "POST");
      curl_easy_setopt(curlHandler, CURLOPT_POSTFIELDS,  
                json_object_to_json_string(jObj));

      /* Perform the request */ 
      CURLcode res = curl_easy_perform(curlHandler);

      /* Check for errors */ 
      if(res != CURLE_OK)
        fprintf(stderr, "CURL failed: %s\n",
                curl_easy_strerror(res));

      /* Clean up */ 
      curl_easy_cleanup(curlHandler);
      json_object_object_del(jObj, "name");
      free(jObj);
  }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)