您的位置:首页 > 编程语言 > C语言/C++

C/C++在VS2015下使用CURL打开网页GET方式

2017-01-15 16:53 357 查看
用到的文件下载地址:http://download.csdn.net/detail/kupig/9738173
// stdafx.cpp : 只包括标准包含文件的源文件
// MFCApplication3.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息

#include "stdafx.h"
#include <string>
#include <iostream>
#include <assert.h>
#include "curl/curl.h"

#pragma comment(lib, "libcurl.lib")

static size_t getVersionCode(void *ptr, size_t size, size_t nmemb, void *userdata)
{//参数userdata是存放数据的指针  其他三个获取内容
std::string *version = (std::string*)userdata;
version->append((char*)ptr, size * nmemb);

return (size * nmemb);
}
void test()
{
CURL* curl;
CURLcode res;

char buffer[10] = { 0 };
struct curl_slist *headers = NULL;
curl = curl_easy_init();//curl初始化
std::string _version;
if (curl)
{
//headers = curl_slist_append(headers, GetHost(strURL));
headers = curl_slist_append(headers, "Connection:keep-alive");
headers = curl_slist_append(headers, "Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,* / *;q=0.8");
//headers = curl_slist_append(headers, UA);    //模拟浏览器
headers = curl_slist_append(headers, "Content-type:application/x-www-form-urlencoded");
//headers = curl_slist_append(headers, RFURL);
//headers = curl_slist_append(headers, "Accept-Encoding: none");//不接受gzip加密
//headers = curl_slist_append(headers, "Accept-Encoding: gzip,deflate");
headers = curl_slist_append(headers, "Accept-Language:zh-CN,zh;q=0.8");

curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);//跳过服务器SSL验证,不使用CA证书
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);//验证服务器端发送的证书,默认是 2(高),1(中),0(禁用)
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);//设置301、302跳转跟随location
//curl_easy_setopt(curl, CURLOPT_AUTOREFERER, 1);// 设置自动设置refer字段
//curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10); //设置连接超时时间
//curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);//发送http请求头
curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, "gzip,deflate");//设置CURLOPT_ACCEPT_ENCODING (7.21.8之前为CURLOPT_ENCODING )
//curl_easy_setopt(curl, CURLOPT_COOKIE, "name1=var1; name2=var2;");   //发送cookie值给服务器
curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "./cookies.txt");//设置访问前得到的COOKIES 存放路径 导入
curl_easy_setopt(curl, CURLOPT_COOKIEJAR, "./cookies.txt"); //设置访问后得到的COOKIES 存放路径 导出
//curl_easy_setopt(curl, CURLOPT_USERAGENT, "User-Agent:Mozilla / 4.0 (compatible; MSIE 9.0; Windows NT 6.1; 2Pac; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";

curl_easy_setopt(curl, CURLOPT_URL, "http://www.baidu.com/");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, getVersionCode);//设置处理数据的函数
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &_version);//数据存储的对象指针
res = curl_easy_perform(curl);//curl链接
curl_easy_cleanup(curl);//清除curl

}

//AfxMessageBox(_version.c_str());

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  curl