Как подключить и использовать библиотеку cURL в С++?
Скачай библиотеку cURL с официального сайта curl:
http://curl.haxx.se/download.html
Теперь предстоит её скомилировать. Для этого понадобится mingw32-make.exe
Открой консоль windows (win+r, ‘cmd’) и иди в директорию с распакованным cURL.
C:\minwg\bin\mingw32-make.exe mingw32
После этих нехитрых манипуляций получишь два файла в директории lib – libcurl.a и libcurldll.a
Скопируй их в C:\minwg\lib
а папку include/curl (которая содержит curl.h) в C:\mingw\include
Осталось настроить Eclipse.
Создай новый проект, открой его свойства Project->Properties
Вкладка C/C++ Build -> Settings
На вкладке Tool Settings: GCC C++ Complier -> Miscellaneous добавь флаг
-DCURL_STATICLIB
Чуть ниже, MinGW C++ Linker->Libraries
добавь туда библиотеки (важен порядок в котором они расположены!)
curl
wsock32
wldap32
На этом всё.
Теперь попробуй скомпилировать пример программы, выкачивающей главную страницу Google.ru.
#include <iostream>
#include <curl/curl.h>
using namespace std;
static char errorBuffer[CURL_ERROR_SIZE];
static string buffer;
static int writer(char *data, size_t size, size_t nmemb, std::string *buffer)
{
int result = 0;
if (buffer != NULL)
{
buffer->append(data, size * nmemb);
result = size * nmemb;
}
return result;
}
int main()
{
char url[] = "http://google.ru";
cout << "Retrieving " << url << endl;
CURL *curl;
CURLcode result;
curl = curl_easy_init();
if(!curl)
{
cout << "cant init curl. exit";
return 0;
}
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_HEADER, 1);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curl, CURLOPT_NOBODY, 1);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
result = curl_easy_perform(curl); // as curl_exec
curl_easy_cleanup(curl);
if (result == CURLE_OK)
{
cout << buffer << "\n";
exit(0);
}else{
cout << "Error: [" << result << "] - " << errorBuffer;
exit(-1);
}
}
Comments Off
No comments yet.
Sorry, the comment form is closed at this time.