使用curl和json-c从C调用json webservice [英] calling a json webservice from C using curl and json-c

查看:750
本文介绍了使用curl和json-c从C调用json webservice的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要调用一个接受json对象的restful webservice。
我能够找到像 libcurl 这样的库来从C应用程序调用webservice。我也可以找到像 json-c 这样的库来在C中创建一个json对象。

I need to call a restful webservice that accepts json object. I was able to find libraries like libcurl to call a webservice from C application. I was also able to find libraries like json-c to create a json object in C.

libcurl接受一个字符串并将其发布到给定webservice url。还有,我可以发布使用json-c库创建的json对象,并使用curl库调用webservice。

libcurl accepts a string and posts it to the given webservice url. Is there anyway that I can post the json object created by using json-c libraries and call the webservice using the curl libraries.

请让我知道如果有任何其他

Please let me know if there is any other library that will allow me both, to create a json object and call a webservice or any other alternate solution.

感谢您提前的帮助。

推荐答案

以下是使用这两个库的示例:

Here is an example using both libraries :

#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;
}

这篇关于使用curl和json-c从C调用json webservice的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆