C++的Curl帖子请求不成功,也没有出错

问题描述 投票:0回答:1

我想做一个简单的命令行程序,用于向同一网络上的另一台计算机进行邮件请求。在这台计算机上,我将读取消息与大力士,以后我会考虑如何从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;
}

谢谢你!我想做一个简单的项目。

c++ curl post
1个回答
0
投票

我解决了这个错误。我没有加载需要的dll。

我把libcurl,libcrypto和libssl dlls添加到debugrelease文件夹中,然后它就工作了,还有这个.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

谢谢你!

© www.soinside.com 2019 - 2024. All rights reserved.