将HTTP字符串发送到服务器后,如何在C ++中使用Curl获取HTTP响应字符串

问题描述

在C ++程序中,我需要使用Curl将HTTP消息发送到另一台运行用C ++编写的REST服务器的计算机,然后从该服务器收集响应。

我对使用Curl并不陌生,并且一直在网上查看文档和各种示例。

我的程序的源代码如下。

将消息发送到服务器是可行的,但是我没有得到服务器发送给我的响应(不是超时问题)。

我很乐意为此提供帮助,因为我不确定用于获取服务器响应的代码是否正确。


#include <stdio.h>
#include <iostream>
#include <unistd.h>
#include <sstream>
#include <curl/curl.h>



size_t getAnswerFunction(void* ptr,size_t size,size_t nmemb,std::string* data) {
    data->append((char*)ptr,size * nmemb);
    return size * nmemb;
}



void sendDataAndGetAnswer(std::string data)
{
  CURL *curl;
  CURLcode res;
  struct curl_slist *httpHeaders=NULL;

  curl = curl_easy_init();
  if (curl)
  {
    curl_global_init(CURL_GLOBAL_ALL);
    curl_easy_setopt(curl,CURLOPT_URL,"http://192.168.0.100:15000");
    curl_easy_setopt(curl,CURLOPT_POSTFIELDS,data.c_str());
    
    httpHeaders = curl_slist_append(httpHeaders,"MyProgram-Header");

    curl_easy_setopt(curl,CURLOPT_HTTPHEADER,httpHeaders);
    curl_easy_setopt(curl,CURLOPT_USERAGENT,"MyAgent/1.0");
    curl_easy_setopt(curl,CURLOPT_POST,1L);
    curl_easy_setopt(curl,CURLOPT_TIMEOUT_MS,1000);

    // .........................................
    // MyProgram sends data.
    // This works right.
    // .........................................

    res = curl_easy_perform(curl);
    if (res != CURLE_OK)
      std::cout << "curl_easy_perform() failed to send message: " << curl_easy_strerror(res) << std::endl;


    // .........................................
    // MyProgram get answer.
    // This does not work.
    // .........................................

    std::string response_string;
    curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,getAnswerFunction);
    curl_easy_setopt(curl,CURLOPT_WRITEDATA,&response_string);
    // getAnswerFunction waits at most 5000 ms.
    // Afterwards,the flow of the program should continue even if there is no response.
    curl_easy_setopt(curl,5000);

    res = curl_easy_perform(curl);
    if (res == CURLE_OK)
      std::cout << response_string;
    else
      std::cout << "curl_easy_perform() failed to get answer: " << curl_easy_strerror(res) << std::endl;


    curl_easy_cleanup(curl);
    curl_slist_free_all(httpHeaders);
  }
}



int main(void)
{

  while (1)
  {
    int valueVar = 0;
    // Execute various statements and perform calculations.
    // ...

    // Calculate value here.
    // ...

    std::string msgToSend("CONTITION-IS-TRUE");
    if (valueVar = 5)
      sendDataAndGetAnswer(msgToSend);
    
    sleep(10);
  }


  return 0;
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)