Chinaunix首页 | 论坛 | 博客
  • 博客访问: 496881
  • 博文数量: 111
  • 博客积分: 3160
  • 博客等级: 中校
  • 技术积分: 1982
  • 用 户 组: 普通用户
  • 注册时间: 2010-04-24 11:49
个人简介

低调、勤奋。

文章分类

全部博文(111)

文章存档

2014年(2)

2013年(26)

2012年(38)

2011年(18)

2010年(27)

分类: C/C++

2013-02-06 22:24:26

以下内容有参考:http://dewei.iteye.com/blog/1572016 


另推荐vc助手,vs编程必备:

项目中需要调用http接口,采用该库较为简单,先记录调用方法。

下载libcurl,http://curl.haxx.se/download/libcurl-7.18.0-win32-msvc.zip,将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;
}



阅读(4418) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~