I'm learning how to use CURL properly, and according to all the examples (the documentation is a pain) my code should work, but for some reason sometimes it connects and other times it won't.
I did check if there was a firewall problem, or the antivirus interfering, but both are turn off and the problem persists.
The main idea is to connect to a local server (rpi), and in the future to an external server for backup/updates.
My code is as follows. Here's the callback function, and the actual function that does all the work, the different URLs are for example purposes.
static std::size_t callback(const char* in,std::size_t size, std::size_t num, std::string* out){
Silo* silo = new Silo();
const std::size_t totalBytes(size * num);
std::string data = std::to_string(totalBytes);
silo->Log("Total Bytes recive " + QString::fromStdString(data));
out->append(in, totalBytes);
return totalBytes;
}
void Server::RPI_Request(){
Silo* silo = new Silo();
//curl_global_init(CURL_GLOBAL_ALL);
CURL *curl = curl_easy_init();
const std::string url_A("http://date.jsontest.com/");
const std::string url_B("https://jsonplaceholder.typicode.com/todos/1");
const std::string url_C("https://www.google.com/");
const std::string url_D("https://stackoverflow.com/");
if (curl){
CURLcode res;
// set Ip Direction
curl_easy_setopt(curl, CURLOPT_URL, url_C.c_str() );
// Don't bother trying IPv6, which would increase DNS resolution time.
curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
// Don't wait forever, time out after 10 seconds.
silo->Log("antes de timeout");
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);
// Follow HTTP redirects if necessary.
//curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
// Response information.
long httpCode(0);
std::unique_ptr<std::string> httpData(new std::string());
// Hook up data handling function.
silo->Log("antes de write function");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback);
// Hook up data container (will be passed as the last parameter to the
// callback handling function). Can be any pointer type, since it will
// internally be passed as a void pointer.
curl_easy_setopt(curl, CURLOPT_WRITEDATA, httpData.get());
// Run our HTTP GET command, capture the HTTP response code, and clean up.
silo->Log("antes de easy perform");
res = curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode);
silo->Log("Respuesta de httpCode: " + QString::number(httpCode));
if (res != CURLE_OK){
silo->Log("Hay pedo no se conecto " + QString::fromStdString(url_C) );
} else {
silo->Log("Coneccion establecida con " + QString::fromStdString(url_C));
}
curl_easy_cleanup(curl);
//curl_global_cleanup();
}
}