首页 技术 正文
技术 2022年11月14日
0 收藏 817 点赞 2,768 浏览 1528 个字

简单的一个curl小例子:

#include <iostream>
#include <string>
#include <sstream>
#include <curl/curl.h>
#include <string.h>#define BUF_SIZE 1024 * 100
using namespace std;string DownloadString(char* url);
int main(int argc, const char* argv[]){ curl_global_init(CURL_GLOBAL_ALL);
cout <<DownloadString("http://www.baidu.com/");
cin.get();
curl_global_cleanup();
return ;
}int WriteData(char* in, size_t size, size_t nmemb, string* out){
out->append(in);
return size*nmemb;
}string DownloadString(char* url){
string buffer;
string headerData;
CURL* conn;
curl_slist* header = NULL;
header = curl_slist_append(header, "Accept-Encoding: gzip, deflate");
header = curl_slist_append(header, "User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; CIBA)");
header = curl_slist_append(header, "Connection: Keep-Alive"); conn = curl_easy_init();
curl_easy_setopt(conn, CURLoption::CURLOPT_URL, url);
curl_easy_setopt(conn, CURLoption::CURLOPT_HTTPHEADER, header);
curl_easy_setopt(conn, CURLoption::CURLOPT_ACCEPT_ENCODING, "gzip");
curl_easy_setopt(conn, CURLoption::CURLOPT_WRITEDATA, &buffer);
curl_easy_setopt(conn, CURLoption::CURLOPT_WRITEFUNCTION, WriteData);
curl_easy_setopt(conn, CURLoption::CURLOPT_WRITEHEADER, &headerData); CURLcode code = curl_easy_perform(conn);
if (code != CURLcode::CURLE_OK)
return "";
curl_slist_free_all(header);
curl_easy_cleanup(conn); istringstream istream(headerData.c_str());
string out;
bool isgzip = false;
while (istream.good())
{
getline(istream, out, '\n');
if (!out.empty()){
if (out.find("Content-Encoding") != out.npos && out.find("gzip") != out.npos){
isgzip = true;
}
}
} ///gzip
return buffer;
}

该例子通过curl下载百度首页html与响应头信息,并自动对gzip解码。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,112
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,585
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,431
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,203
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,838
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,922