libcurl使用演示样例

简要说明:C++使用libcurl訪问"www.baidu.com"。获取返回码和打印出http文件

/*
 * @ libcurl使用演示样例
 * @ 2014.04.29
 * @ g++ -o LibCurlFunc LibCurlFunc.cpp -lcurl
 */
#include <iostream>
#include <string.h>
#include <curl/curl.h>
using namespace std;

/* 
	Http请求结束的回调函数
	@ 会被调用多次,有下载到数据(http文件)就回调。直到下载完
 */
static size_t WriteFunction(void *input, size_t uSize, size_t uCount, void *avg)
{
	/* cout << "[WriteFunction]:" << endl
		 << "input=" << (char*)input << endl
		 << "elementSize=" << uSize << endl
		 << "elementCount=" << uCount << endl;*/
		 
	// 将请求返回数据input复制到avg中(avg为一開始curl_easy_setopt设置的參)
	size_t uLen = uSize*uCount;
	// string &sBuffer = *reinterpret_cast<string *>(avg);
	// sBuffer.append(reinterpret_cast<const char *>(input), uLen);
	string *pStr = (string *)(avg);
	pStr->append((char *)(input), uLen);
	
	// 仅仅有返回uSize*uCount才会返回成功
	return uLen;
}

int main()
{
	CURL *pCurl = NULL;
	CURLcode code;
	
	/* CURLcode curl_global_init(long flags)
	   @ 初始化libcurl。全局仅仅需调一次
	   @ flags:	CURL_GLOBAL_DEFAULT 	// 等同于CURL_GLOBAL_ALL 
				CURL_GLOBAL_ALL     	// 初始化全部的可能的调用
				CURL_GLOBAL_SSL     	// 初始化支持安全套接字层
				CURL_GLOBAL_WIN32   	// 初始化win32套接字库
              	CURL_GLOBAL_NOTHING 	// 没有额外的初始化
			    ......
	 */
	code = curl_global_init(CURL_GLOBAL_DEFAULT);
	if (code != CURLE_OK) {
		cout << "curl_global_init() Err" << endl;
		return -1;
	}
	
	/* CURL *curl_easy_init()
	   @ 初始化curl生成CURL *curl指针
	 */
	pCurl = curl_easy_init();
	if (pCurl == NULL) {
		cout << "curl_easy_init() Err" << endl;
		return -1;
	}
	
	string sUrl = "www.baidu.com";
	curl_slist *pHeaders = NULL;
	string sBuffer;
	
	/* struct curl_slist *curl_slist_append(struct curl_slist * list, const char * string);
	   @ 加入Http消息头
	   @ 属性string:形式为name+": "+contents
	 */
	string header = "username: andyawang";
	pHeaders = curl_slist_append(pHeaders, header.c_str());
	
	/* CURLcode curl_easy_setopt(CURL *handle, CURLoption option, parameter);
	   @ 设置下载属性及经常使用參数
	 */
	curl_easy_setopt(pCurl, CURLOPT_URL, "www.baidu.com"); 	// 訪问的URL
	curl_easy_setopt(pCurl, CURLOPT_HTTPHEADER, pHeaders);  // 属性头部(要不pHeader就没用了)
	curl_easy_setopt(pCurl, CURLOPT_TIMEOUT, 20); 			// 超时(单位S)
	curl_easy_setopt(pCurl, CURLOPT_HEADER, 1); 			// 下载数据包含HTTP头部
	
	curl_easy_setopt(pCurl, CURLOPT_WRITEFUNCTION, &WriteFunction);	// !数据回调函数
	curl_easy_setopt(pCurl, CURLOPT_WRITEDATA, &sBuffer);			// !数据回调函数的參。一般为Buffer或文件fd
	
	/* CURLcode curl_easy_perform(CURL *handle);
	   @ 開始下载
	 */
	code = curl_easy_perform(pCurl);
	if (code != CURLE_OK) {
		cout << "curl_easy_perform() Err" << endl;
		return -1;
	}
	
	/* CURLcode curl_easy_getinfo(CURL *curl, CURLINFO info, ... );
	   @ 获取下载完的相关信息
	   @ info:CURLINFO_RESPONSE_CODE  	// 获取返回的Http码
			   CURLINFO_TOTAL_TIME  	// 获取总的请求下载时间
			   CURLINFO_SIZE_DOWNLOAD  	// 获取下载的文件大小
			   ......
	 */
	long retCode = 0;
	code = curl_easy_getinfo(pCurl, CURLINFO_RESPONSE_CODE , &retCode); 
	if (code != CURLE_OK) {
		cout << "curl_easy_perform() Err" << endl;
		return -1;
	}
	cout << "[Http Return Code] : " << retCode << endl;
	cout << "[Http Context] : " << endl << sBuffer << endl;
	
	/* void curl_easy_cleanup(CURL * handle);
	   @ 释放CURL *curl指针
	 */		
	curl_easy_cleanup(pCurl);
	
	/* void curl_global_cleanup(void);
	   @ 初始化libcurl,全局也仅仅需调一次
	 */		
	curl_global_cleanup();
}

执行结果:

gapp_devnet_1:/data/home/andyawang/code/Components/Http # g++ -o LibCurlFunc LibCurlFunc.cpp -lcurl
gapp_devnet_1:/data/home/andyawang/code/Components/Http # ./LibCurlFunc 
[Http Return Code] : 200
[Http Context] : 
HTTP/1.0 200 OK
Date: Wed, 30 Apr 2014 02:41:35 GMT
Content-Type: text/html; charset=utf-8
Vary: Accept-Encoding
Set-Cookie: BAIDUID=8DD8F93E631536AD6CDC010E1A52507C:FG=1; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com
Set-Cookie: BDSVRTM=0; path=/
Set-Cookie: H_PS_PSSID=5695_1428_5225_6024_4760_6018_6256_6311_6269; path=/; domain=.baidu.com
P3P: CP=" OTI DSP COR IVA OUR IND COM "
Cache-Control: private
Expires: Wed, 30 Apr 2014 02:41:33 GMT
X-Powered-By: HPHP
Server: BWS/1.1
BDPAGETYPE: 1
BDQID: 0x9fcc512a0001374f
BDUSERID: 0
X-Cache: MISS from qplus_wanproxy_pub_fy1
Via: 1.0 qplus_wanproxy_pub_fy1 (squid/3.1.18)
Connection: close

<!DOCTYPE html><!--STATUS OK--><html><head><meta http-equiv="content-type" content="text/html;charset=utf-8"><link rel="dns-prefetch" href="//s1.bdstatic.com"/><link rel="dns-prefetch" href="//t1.baidu.com"/><link rel="dns-prefetch" href="//t2.baidu.com"/><link rel="dns-prefetch" href="//t3.baidu.com"/><link rel="dns-prefetch" href="//t10.baidu.com"/><link rel="dns-prefetch" href="//t11.baidu.com"/><link rel="dns-prefetch" href="//t12.baidu.com"/><title>百度一下。你就知道</title><style >html,body{height:100%}html{overflow-y:auto}#wrapper{position:relative;_position:;min-height:100%}#content{padding-bottom:100px;text-align:center}#ftCon{height:100px;position:absolute;bottom:44px;text-align:center;width:100%;margin:0 auto;
......




posted @ 2016-03-22 20:03  zfyouxi  阅读(218)  评论(0编辑  收藏  举报