C++Socket编程—Libcurl库
标签:编程 xhtml dde cal agent ons lang set list
一、LibCurl基本编程框架
libcurl是一个跨平台的网络协议库,支持http, https, ftp, gopher, telnet, dict, file, 和ldap 协议。libcurl同样支持HTTPS证书授权,HTTP POST, HTTP PUT, FTP 上传, HTTP基本表单上传,代理,cookies,和用户认证.
win32版的libcurl下载地址:http://curl.freeby.pctools.cl/download/libcurl-7.18.0-win32-msvc.zip
代码示例:调用libcurl模拟发送http包,并获取位置
#include
#include "curl/curl.h"
#include
#pragma comment(lib, "libcurl.lib")
using namespace std;
const char* UTF8_To_GBK(const char* source, char* pcDes);
string strUtf8;
size_t WriteCallback(char* ptr, size_t size, size_t nmemb, void* userdata)
{
//printf(ptr);
strUtf8 += ptr;
return size * nmemb; //处理了所有的数据
}
//初始化库,进程生命周期只调用一次
curl_global_init(CURL_GLOBAL_ALL);
/*
发送请求
*/
//创建请求的句柄
CURL* handle = curl_easy_init();
//设置url
CURLcode nRetCode=curl_easy_setopt(handle, CURLOPT_URL, "http://ip.tool.chinaz.com/");
//设置代理,是fidder可以抓到包
nRetCode = curl_easy_setopt(handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
//设置处理响应包的回调函数
nRetCode=curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, WriteCallback);
//设置为fidder的代理地址
nRetCode = curl_easy_setopt(handle, CURLOPT_PROXY, "127.0.0.1:8888");
//为请求添加头部
curl_slist* chunk = NULL;
chunk = curl_slist_append(chunk, "Host: ip.tool.chinaz.com");
chunk = curl_slist_append(chunk, "User-Agent: Mozilla / 5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko / 20100101 Firefox / 75.0");
chunk = curl_slist_append(chunk, "Accept : text / html, application / xhtml + xml, application / xml; q = 0.9, image / webp, */*;q=0.8");
chunk = curl_slist_append(chunk, "Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
//chunk = curl_slist_append(chunk, "Accept-Encoding: gzip, deflate");//免解压缩
chunk = curl_slist_append(chunk, "Connection: keep-alive");
chunk = curl_slist_append(chunk, "Upgrade-Insecure-Requests: 1");
curl_easy_setopt(handle, CURLOPT_HTTPHEADER, chunk);
//发送请求
nRetCode = curl_easy_perform(handle);
//处理数据
char* pBuff = new char[strUtf8.size()];
UTF8_To_GBK(strUtf8.c_str(), pBuff);
//printf(pBuff);
string strGbk = pBuff;
delete[] pBuff;
//正则查找位置
size_t nOff = strGbk.find("来自");
size_t nOffBegin = strGbk.find("", nOff);
size_t nOffEnd = strGbk.find("
C++Socket编程—Libcurl库
标签:编程 xhtml dde cal agent ons lang set list
原文地址:https://www.cnblogs.com/zhaoyixiang/p/12798731.html
评论