使用POCO进行C++的Http请求

11

我想知道如何使用 POCO 在 C++ 中请求 URL(例如下载图片并保存)?

到目前为止,我有这段小代码:

#include <iostream>
#include <string>
#include "multiplication.h"
#include <vector>
#include <HTTPRequest.h>
using std::cout;
using std::cin;
using std::getline;

using namespace Poco;
using namespace Net;

int main() {
    HTTPRequest *test = new HTTPRequest("HTTP_GET", "http://www.example.com", "HTTP/1.1");
}

只是额外的信息,我能够在Windows cygwin环境中编译上面的代码。首先安装以下cygwin软件包:libpoco-devellibpoco49。然后通过以下方式编译上面的C++片段:g++ -o snippet snippet.cpp -L/usr/lib/ -l:libPocoFoundation.dll.a -l:libPocoNet.dll.a -I/usr/include/Poco/Net - daparic
1个回答

36

通常情况下,即使你对POCO一无所知,也不需要像使用boost/asio那样具备中高级C++知识(例如“enable_share_from_this”是什么意思),POCO仍然具有非常简单的优势。

在POCO“安装目录”下可以找到示例目录(例如,在我的情况下是poco\poco-1.4.6p4\Net\samples\httpget\src)。

在线帮助浏览也很容易和快速(例如浏览类)。

如果您当前对C++的理解还不足够,请去大学图书馆借阅Scott Meyers的著作(Effective C++以及More effective C++之后)。

因此,我们将示例代码 httpget.cpp 调整为最小要求。

在主函数内部:

URI uri("http://pocoproject.org/images/front_banner.jpg");
std::string path(uri.getPathAndQuery());
if (path.empty()) path = "/";
HTTPClientSession session(uri.getHost(), uri.getPort());
HTTPRequest request(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
HTTPResponse response;

if (!doRequest(session, request, response))
{
    std::cerr << "Invalid username or password" << std::endl;
    return 1;
}

并且这个函数几乎没有被改动:

bool doRequest(Poco::Net::HTTPClientSession& session,
               Poco::Net::HTTPRequest& request,              
               Poco::Net::HTTPResponse& response)
{
    session.sendRequest(request);
    std::istream& rs = session.receiveResponse(response);
    std::cout << response.getStatus() << " " << response.getReason() << std::endl;
    if (response.getStatus() != Poco::Net::HTTPResponse::HTTP_UNAUTHORIZED)
    {
        std::ofstream ofs("Poco_banner.jpg",std::fstream::binary); 
        StreamCopier::copyStream(rs, ofs);
        return true;
    }
    else
    {
        //it went wrong ?
        return false;
    }
}

我让你安排好事情,看看图像会落在你的硬盘上哪里。

希望能帮到你。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接