2016/11/17
6,647
libcurl 是一个免费开源的 客户端 的网络传输库,它支持多种协议,包括
DICT, FILE, FTP, FTPS, Gopher, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMTP, SMTPS, Telnet and TFTP等,还支持 SSL 认证。它简单好用,用它自己的话来说,就是 free, thread-safe, IPv6 compatible, feature rich, well supported, fast, thoroughly documented and is already used by many known, big and successful companies and
numerous applications。
1 基本流程
使用 libcurl 的一般流程:
- curl_global_init() 进行库的初始化
- curl_easy_init() 获取CURL* 指针
- curl_easy_setopt() 设置传输参数,包括回调等
- curl_easy_perform() 完成传输
- curl_easy_cleanup() 释放内存
- curl_global_cleanup() 释放库内存
我们需要着重关心的,是第 3 步。在这一步里,我们将指定 libcurl 如何将参数传递给服务端。
1.1 简单示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
#include <iostream> #include "curl/curl.h" using namespace std; size_t read_callback(char *buffer, size_t size, size_t nitems, void *instream) { cout << buffer << endl; return size * nitems; } int main(void) { curl_global_init(CURL_GLOBAL_ALL); CURL* handle = curl_easy_init(); if (!handle) { cout << "curl_easy_init error" << endl; } struct curl_slist* headers = NULL; curl_slist_append(headers, "user-agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) \ Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0"); curl_slist_append(headers, "accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); curl_easy_setopt(handle, CURLOPT_URL, "http://curl.haxx.se/"); curl_easy_setopt(handle, CURLOPT_HEADER, 1L); curl_easy_setopt(handle, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(handle, CURLOPT_READFUNCTION, read_callback); CURLcode status = curl_easy_perform(handle); if (status != CURLE_OK) { cout << "curl_easy_perform Error:" << status << endl; } curl_easy_cleanup(handle); curl_global_cleanup(); return 0; } |