libcurl之初体验

来源:互联网 发布:网页游戏制作软件 编辑:程序博客网 时间:2024/06/05 06:41
#include <iostream>#include <curl/curl.h>#include <string>using std::cout;using std::endl;size_t string_write(void* content,size_t size,size_t nmemb,void* userp){((std::string*)userp)->append((char*)content,size*nmemb);return size*nmemb;}CURLcode read_content_from_url(const std::string& url,std::string* content,long time_out=30){CURLcode code(CURLE_FAILED_INIT);CURL* curl=curl_easy_init();if(curl){if(CURLE_OK==(code=curl_easy_setopt(curl,CURLOPT_URL,url.c_str())) //不用讲&& CURLE_OK==(code=curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,string_write)) //不用讲&& CURLE_OK==(code=curl_easy_setopt(curl,CURLOPT_WRITEDATA,content))  //不用讲&& CURLE_OK==(code=curl_easy_setopt(curl,CURLOPT_TIMEOUT,time_out))  //延迟&& CURLE_OK==(code=curl_easy_setopt(curl,CURLOPT_FOLLOWLOCATION,1L)) //跟进&& CURLE_OK==(code=curl_easy_setopt(curl,CURLOPT_NOPROGRESS,1L))) //不要进度条{code=curl_easy_perform(curl);}curl_easy_cleanup(curl);}return code;}int main(int argc,char* argv[]){std::string content;std::string url("http://www.baidu.com");CURLcode code=read_content_from_url(url,&content);if(code==CURLE_OK){cout<<content<<endl;}else{std::cerr<<"Error: "<<curl_easy_strerror(code)<<endl;}return 0;}

原创粉丝点击