简体   繁体   中英

cURL & C++ (libcurl?)

I'm sort of confused to go about taking a simple shell script I made and compile it into an exe in C++. The problem I'm running into now and have researched to no avail is how to get cURL to work in conjunction with C++. Essentially, I want to have a user input a url, store it in a string and then use it in the following line to detect if there is a url redirection.

var url,
cout<<"Please enter a URL to detect if there is a redirect."<<endll
cin<<URL;
curl -b cookies -w "%{url_effective}\n" -L -s -S -o /dev/null URL      // <-   http://website.com/page/Redirected_PATH/

Is there any way I can import a header file to support the previous cURL flags I was using previously in the terminal?

Thank you for any insight.

Curl has a library called libcurl that allows you to interface with curl directly without having to go through the command line. Here's a sample for sending data to a URL:

extern "C" {
#include <curl/curl.h>
}

size_t CurlReadFunction(void *ptr, size_t size, size_t nmemb, void *userdata)
{
    stringstream& ssData = *(stringstream*)userdata;
    string sData = ssData.str();
    size_t iBytesToRead = sData.size() - ssData.tellp();

    if (iBytesToRead > nmemb)
        iBytesToRead = nmemb;

    memcpy(ptr, sData.data() + ssData.tellp(), iBytesToRead);
    ssData.seekp((size_t)ssData.tellp() + iBytesToRead);
    return iBytesToRead;
}

///... then when you want to send your data

curl_global_init(CURL_GLOBAL_ALL);

CURL* pCurl = curl_easy_init();
if (!pCurl)
    return;

curl_easy_setopt(pCurl, CURLOPT_TIMEOUT, 10L);
curl_easy_setopt(pCurl, CURLOPT_NOSIGNAL, 1L);
curl_easy_setopt(pCurl, CURLOPT_URL, "http://example.com/receive.php");
curl_easy_setopt(pCurl, CURLOPT_UPLOAD, 1);
curl_easy_setopt(pCurl, CURLOPT_READDATA, &ssData);
curl_easy_setopt(pCurl, CURLOPT_READFUNCTION, CurlReadFunction);
curl_easy_setopt(pCurl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)sData.size());

CURLcode eRes = curl_easy_perform(pCurl);
if(eRes == CURLE_OK)
    //success
else
    cout << "curl_easy_perform() failed: " << curl_easy_strerror(eRes) << "\n";

curl_easy_cleanup(pCurl);
curl_global_cleanup();

I realize that's nothing like what you want to do, but anything that's possible with curl should also be possible with the libcurl API. Then you link against libcurl.lib and you're done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM