http connection with c ++ and curl or any other library

1

I need to do url https and http request. I found several libraries, some easy, some not so much, but the only one I could install was the curl. I have already taken several examples, the problem is that in the examples they are using structured language, and I am implementing this in qtcreator that uses object orientation. I got the code on the following website: link

The code looks like this form1.h

#ifndef FORM1_H
#define FORM1_H
#include <QMainWindow>
#include <iostream>
#include <string>
#include <curl/curl.h>

using namespace std;

namespace Ui {
    class Form1;
}

class Form1 : public QMainWindow
{
        Q_OBJECT

        public:
            explicit Form1(QWidget *parent = 0);
            string readBuffer;
            CURL *curl;
            CURLcode res;
            size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
            {
                ((string*)userp)->append((char*)contents, size * nmemb);
                return size * nmemb;
            }

            ~Form1();



        private slots:
            void on_btnLogin_clicked();

        private:
            Ui::Form1 *ui;
        };

        #endif // FORM1_H

form1.cpp

#include "form1.h"
#include "ui_form1.h"
#include <QWebView>
#include <iostream>
#include <stdio.h>
#include <curl/curl.h>
#include <string>
using namespace std;

Form1::Form1(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Form1)
    {
        ui->setupUi(this);
        this->curl = curl_easy_init();
    }

Form1::~Form1()
{
    delete ui;
}

void Form1::on_btnLogin_clicked()
{
    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "http://www.google.com");
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        cout << readBuffer << std::endl;
}

The error is as follows

form1.cpp:35: error: invalid use of member function (did you forget the '()' ?)
     curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);'
    
asked by anonymous 29.06.2017 / 03:29

1 answer

1

The error is occurring because the third argument ( WriteCallback ) passed in the curl_easy_setopt(CURLOPT_WRITEFUNCTION) call is a class method and not a pointer to a function.

One way to solve this would be to make the% static method static, which makes it behave like a function:

static size_t WriteCallback( void *contents, size_t size, size_t nmemb, void *userp )
{
    ((string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
}

And change the call from WriteCallback to:

curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, Form1::WriteCallback );
    
29.06.2017 / 15:43