libcurl之curl_easy_getinfo的使用教程

执行结果


libcurl之curl_easy_getinfo的使用教程_第1张图片

代码


// getinfo.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include 
using namespace std;
#include "curl/curl.h"
#pragma comment(lib, "curllib.lib")

//回调函数
size_t process_data(void *buffer, size_t size, size_t nmemb, void *user_p)
{
	FILE *fp = (FILE *)user_p;
	size_t return_size = fwrite(buffer, size, nmemb, fp);
	//cout << (char *)buffer << endl;
	return return_size;
}

void print_cookies(CURL *curl)
{
	CURLcode res;
	struct curl_slist *cookies;
	struct curl_slist *nc;
	int i;

	printf("Cookies, curl knows:\n");
	res = curl_easy_getinfo(curl, CURLINFO_COOKIELIST, &cookies);
	if (res != CURLE_OK) {
		fprintf(stderr, "Curl curl_easy_getinfo failed: %s\n", curl_easy_strerror(res));
		exit(1);
	}
	nc = cookies, i = 1;
	while (nc) {
		printf("[%d]: %s\n", i, nc->data);
		nc = nc->next;
		i++;
	}
	if (i == 1) {
		printf("(none)\n");
	}
	curl_slist_free_all(cookies);
}

int _tmain(int argc, _TCHAR* argv[])
{
	// 初始化libcurl
	CURLcode return_code;
	return_code = curl_global_init(CURL_GLOBAL_WIN32);
	if (CURLE_OK != return_code)
	{
		cerr << "init libcurl failed." << endl;
		return -1;
	}

	// 获取easy handle
	CURL *easy_handle = curl_easy_init();
	if (NULL == easy_handle)
	{
		cerr << "get a easy handle failed." << endl;
		curl_global_cleanup(); 
		return -1;
	}

	FILE *fp = fopen("data.html", "ab+");
	char *url = "http://blog.csdn.com/php_fly";	
	//char *url = "http://www.csdn.com";	

	// 设置easy handle属性
	curl_easy_setopt(easy_handle, CURLOPT_URL, url);
	curl_easy_setopt(easy_handle, CURLOPT_WRITEFUNCTION, &process_data);
	
	// curl_easy_setopt(easy_handle, CURLOPT_VERBOSE, 1L);
	//curl_easy_setopt(easy_handle, CURLOPT_COOKIEFILE, ""); /* just to start the cookie engine */

	//fp:回调函数的参数
	curl_easy_setopt(easy_handle, CURLOPT_WRITEDATA, fp);

	// 执行数据请求
	return_code = curl_easy_perform(easy_handle);
	if (return_code != CURLE_OK)
	{
		printf( "Failed to get '%s' [%s]\n",url, return_code);
		return 0;
	}

	//////////////////////////////////////////////////////////////////////////
	int totalTime = 0;
	return_code = curl_easy_getinfo(easy_handle,CURLINFO_TOTAL_TIME,&totalTime);
	if((CURLE_OK==return_code) && totalTime)
		cout<<"耗时:"<

版权

原文地址: 曾是土木人

你可能感兴趣的:(C++)