c/c++语言开发共享使用curl和json-c从C调用json webservice

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

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

如果有任何其他库允许我同时创建一个json对象并调用webservice或任何其他替代解决方案,请告诉我。

感谢您的帮助。

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

    #include  #include  #include  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, "https://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: %sn", curl_easy_strerror(res)); /* Clean up */ curl_easy_cleanup(curlHandler); json_object_object_del(jObj, "name"); free(jObj); } return 0; } 

    使用json-c中的以下函数将json对象转换为字符串,并将其包含在curl请求的正文中。

     #include "json.h" const char* json_object_to_json_string(struct json_object *obj); 

    在这里查看HTTP POST的示例(您可能需要使用PUT或DELETE,具体取决于您要连接的Web服务以及您要执行的操作)

      以上就是c/c++开发分享使用curl和json-c从C调用json webservice相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/549267.html

      (0)
      上一篇 2021年1月14日
      下一篇 2021年1月14日

      精彩推荐