/* * Copyright (c) 2023 by Thomas A. Early N7TAE * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "CurlGet.h" CCurlGet::CCurlGet() { curl_global_init(CURL_GLOBAL_ALL); } CCurlGet::~CCurlGet() { curl_global_cleanup(); } // callback function writes data to a std::ostream size_t CCurlGet::data_write(void* buf, size_t size, size_t nmemb, void* userp) { if(userp) { std::ostream& os = *static_cast(userp); std::streamsize len = size * nmemb; if(os.write(static_cast(buf), len)) return len; } return 0; } CURLcode CCurlGet::GetURL(const std::string &url, std::stringstream &ss, long timeout) { CURLcode code(CURLE_FAILED_INIT); CURL* curl = curl_easy_init(); if(curl) { if(CURLE_OK == (code = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &data_write)) && CURLE_OK == (code = curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L)) && CURLE_OK == (code = curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L)) && CURLE_OK == (code = curl_easy_setopt(curl, CURLOPT_FILE, &ss)) && CURLE_OK == (code = curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout)) && CURLE_OK == (code = curl_easy_setopt(curl, CURLOPT_URL, url.c_str()))) { code = curl_easy_perform(curl); } curl_easy_cleanup(curl); } if (code != CURLE_OK) { std::cout << "WARNING: was not able retrieve data at '" << url << "'\nCurl returned: " << code << std::endl; } return code; }