我正在尝试做一个简单的命令行程序,以向同一网络上的另一台计算机发出发布请求。在这台计算机上,我将阅读Hercules上的消息,然后再考虑如何从c ++代码中读取它。我正在使用QtCreator和mingw x64。
运行小型项目Qt时,打开控制台,但立即看到控制台显示“按回车键关闭窗口”。代码有什么问题?
#include <iostream>
#include <curl/curl.h>
#include <string>
#include <cstdio>
#include <cstring>
#include <functional>
using namespace std;
class ScopeExit {
public:
ScopeExit(std::function<void()> f): f_(f) {}
~ScopeExit() { f_(); }
private:
std::function<void()> f_;
};
struct PostData
{
const char *ptr;
size_t size;
};
size_t read_data(void* ptr, size_t size, size_t nmemb, void *userp)
{
PostData *post_data = (PostData*)userp;
size_t byte_len = size * nmemb;
if(post_data->size < byte_len)
{
byte_len = post_data->size;
}
memcpy(ptr, post_data->ptr, byte_len);
post_data->ptr += byte_len;
post_data->size -= byte_len;
return byte_len;
}
static size_t WriteCallback(void *contents, size_t size, size_t nmeb, void *userp)
{
((std::string*)userp)->append((char*)contents, size * nmeb);
return size * nmeb;
}
void post_request(std::string ipPort,std::string message)
{
// EXCECUTION START HERE
std::cout<<"Setting up request data!"<<std::endl;
CURL *curl = curl_easy_init();
if(!curl)
{
std::cout<<"curl_easy_init() failed"<<std::endl;
}
ScopeExit curl_close([&curl] {
curl_easy_cleanup(curl);
});
curl_easy_setopt(curl, CURLOPT_URL, ipPort.c_str());
// set http method to POST
curl_easy_setopt(curl, CURLOPT_POST, 1L);
const char *msg = message.c_str();
PostData post_data;
post_data.ptr = msg;
post_data.size = strlen(msg);
curl_easy_setopt(curl, CURLOPT_READDATA, &post_data);
curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_data);
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strlen(msg));
// set callback on receiving data
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, stdout);
// execute
CURLcode res = curl_easy_perform(curl);
if(res != CURLE_OK)
{
std::cout<<"Error on curl_easy_perform: "<< curl_easy_strerror(res)<<std::endl;
}
}
int main()
{
std::string ipPort;
std::string message;
std::cout<<"Insert destination ip with port: ";
std::cin>>ipPort;
std::cout<<std::endl;
std::cout<<"Insert messagge: ";
std::cin>>message;
std::cout<<std::endl;
std::cout<<"Press p for doing a post request"<<std::endl;
post_request("http://192.168.1.23:55231","hello");
return 0;
}
谢谢!
答案 0 :(得分:0)
我解决了错误。我没有加载所需的dll。
我将libcurl,libcrypto和libssl dll添加到了debug / release文件夹,并且可以通过以下.pro文件工作:
TEMPLATE = app
CONFIG += console c++11
CONFIG -= app_bundle
CONFIG -= qt
SOURCES += \
main.cpp
INCLUDEPATH += path/to/curl/include
LIBS += -Lpath/to/curl/lib/folder -lcurl
谢谢!