libcurl 发送 post 请求,请求体为 json 格式

傷城~ 2021-09-25 00:48 1318阅读 0赞

libcurl 发送 post 请求,请求体为 json 格式

安装 libcurl

  1. sudo apt install libcurl

使用 libcurl

使用 jsoncpp 创建 json 格式字符串,如果没有安装 jsoncpp 可以使用 apt install jsoncpp 安装

  1. #define CURL_STATICLIB
  2. #include <curl/curl.h>
  3. #include <jsoncpp/json/json.h>
  4. #include <stdio.h>
  5. #include <string>
  6. #include <iostream>
  7. #include <chrono>
  8. size_t ReceiveData(void *contents, size_t size, size_t nmemb, void *stream)
  9. {
  10. std::string *str = (std::string *)stream;
  11. (*str).append((char *)contents, size * nmemb);
  12. return size * nmemb;
  13. }
  14. CURLcode HttpPost(const std::string &url, const std::string &data, std::string &response, int timeout = 300)
  15. {
  16. CURLcode res;
  17. CURL *curl = curl_easy_init();
  18. struct curl_slist *headers = NULL;
  19. headers = curl_slist_append(headers, "Content-Type:application/json;charset=UTF-8");
  20. if (curl == NULL)
  21. {
  22. return CURLE_FAILED_INIT;
  23. }
  24. // 设置请求地址
  25. curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  26. // 设置请求头信息
  27. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  28. // 不显示接收头信息
  29. curl_easy_setopt(curl, CURLOPT_HEADER, 0);
  30. // 设置请求超时时间
  31. curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, timeout);
  32. // 设置请求体
  33. curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str());
  34. // 设置接收函数
  35. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, ReceiveData);
  36. // 设置接收内容
  37. curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&response);
  38. res = curl_easy_perform(curl);
  39. curl_easy_cleanup(curl);
  40. return res;
  41. }
  42. int main()
  43. {
  44. auto start = std::chrono::system_clock::now();
  45. Json::Value root;
  46. root["text"] = "喂喂喂,你好。";
  47. std::string url = "http://192.168.1.79:9001/api/asr/csc/";
  48. std::string response;
  49. CURLcode res = HttpPost(url, root.toStyledString(), response);
  50. std::chrono::duration<double> duration = std::chrono::system_clock::now() - start;
  51. std::cout << "Post used time: " << duration.count() << "\n";
  52. if (res != CURLE_OK)
  53. {
  54. fprintf(stderr, "Failed: %s\n", curl_easy_strerror(res));
  55. }
  56. duration = std::chrono::system_clock::now() - start;
  57. std::cout << "total used time: " << duration.count() << "\n";
  58. Json::Reader reader;
  59. Json::Value output;
  60. reader.parse(response, output);
  61. std::cout << "checked_sentence: " << output["checked_sentence"].toStyledString() << "\n";
  62. return 0;
  63. }

编译

  1. g++ -std=c++11 main.cc -lcurl -ljsoncpp -o main

参考文章

libcurl 使用示例

发表评论

表情:
评论列表 (有 0 条评论,1318人围观)

还没有评论,来说两句吧...

相关阅读