低调、勤奋。
分类: C/C++
2013-02-06 22:24:26
以下内容有参考:http://dewei.iteye.com/blog/1572016
另推荐vc助手,vs编程必备:
项目中需要调用http接口,采用该库较为简单,先记录调用方法。
下载libcurl,,将dll放到system32目录下,将lib和include文件放到对应的vs2010的安装目录中。
下载zlib,将dll文件放入C:\WINDOWS\system32,下载:
// curl.cpp : 定义控制台应用程序的入口点。
// #include "stdafx.h" #include#include #include #include #include #include #include #pragma comment(lib, "libcurl.lib") using std::string; using std::cout; using std::endl; static const char * const global_useragent = "libcurl-agent/1.0"; size_t call_wirte_func(const char *ptr, size_t size, size_t nmemb, string *stream) { assert(stream != NULL); size_t len = size * nmemb; stream->append(ptr, len); return len; } string open_url(const string& url) { CURL *curl; CURLcode code; string szbuffer; curl_global_init(CURL_GLOBAL_ALL); curl = curl_easy_init(); if (curl) {
//设置超时时间
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5);
//设置url地址
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_USERAGENT, global_useragent);
//设置post值
//curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "username=jordan&secret=test");
//抓取内容后,回调函数
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, call_wirte_func);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &szbuffer);
code = curl_easy_perform(curl);
if (CURLE_OK == code)
{
//执行成功
double val;
/* check for bytes downloaded */
code = curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &val);
if ((CURLE_OK == code) && (val>0))
printf("Data downloaded: %0.0f bytes.\n", val);
}
/* 释放内存 */
curl_easy_cleanup(curl); }
curl_global_cleanup();
return szbuffer;
}
int _tmain(int argc, _TCHAR* argv[])
{
string url = "";
string res = open_url(url);
string::size_type pos;
if (!res.empty())
{
pos = res.find("404 Not Found");
if ( pos != string::npos )
{
cout << "The url is not valid" << endl;
}
else
{
cout << "the url " << url.c_str() << "---return value is---->" << res.c_str() << endl;
}
}
else
{
cout << "sorry, can not get any contents" << endl;
}
system("pause");
return 0;
}