to myself 的分类学习日志

做自己想做的事
posts - 232, comments - 6, trackbacks - 0, articles - 0

cpp-netlib之async_client解析

Posted on 2013-07-15 17:19 kongkongzi 阅读(777) 评论(0)  编辑 收藏 引用 所属分类: c++ network library
cpp-netlib:
参考:
1. http://cpp-netlib.org/
2. https://github.com/cpp-netlib/
3. http://github.com/cpp-netlib/


解析版本: cpp-netlib-0.9.4
注:使用的boost版本为boost_1_53_0。 若使用boost_1_46_1在Windows上编译会出现错误。


testClient.cpp:
#include <boost/shared_ptr.hpp>
#include <boost/network/protocol/http/client.hpp>
#include <iostream>

namespace http = boost::network::http;

using namespace boost::network;


struct body_handler {
    explicit body_handler(void* context)
    : context_(context) {}

    BOOST_NETWORK_HTTP_BODY_CALLBACK(operator(), range, error) {
        // in here, range is the Boost.Range iterator_range, and error is
        
// the Boost.System error code.
        if (!error)
        {
            std::cout << "Received " << boost::distance(range) << "bytes." << std::endl;
            body_.append(boost::begin(range), boost::end(range));
            std::cout << "body: " << body_ << std::endl;
        }
        else
        {
            std::cout << "Error: " << error << std::endl;
        }

        return;
    }

private:
    void* context_;
    std::string body_;
};


int main(int argc, char *argv[]) {
    try {
    }
    catch (std::exception &e) {
        std::cerr << e.what() << std::endl;
        return 1;
    }


    if (argc != 2) {
        std::cout << "Usage: " << argv[0] << " [url]" << std::endl;
        return 1;
    }

    http::client client;
    http::client::request request(argv[1]);
    request << header("Connection", "close");
    http::client::response response = client.get(request, http::_body_handler=body_handler(NULL));
    std::cout << "status: " << http::status(response) << std::endl;

    return 0;
}




只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理