【问题标题】:C++ Http Request with POCO带有 POCO 的 C++ Http 请求
【发布时间】:2014-11-19 05:17:21
【问题描述】:

我想知道如何在 C++ 中使用 POCO 向 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++ sn-p:g++ -o snippet snippet.cpp -L/usr/lib/ -l:libPocoFoundation.dll.a -l:libPocoNet.dll.a -I/usr/include/Poco/Net

标签: c++ http request poco-libraries


【解决方案1】:

通常 POCO 有一个很大的优势是非常简单,即使你对它一无所知,并且你不需要像 boost/asio 那样需要中级/高级 C++ 知识(例如什么意思 enable_share_from_this ...)

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

在线帮助浏览也方便快捷(例如浏览课程)。

如果你目前对C++的理解还不够,去大学图书馆借Scott Meyers的书(Effective C++ and after 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;
    }
}

我让你为你安排事情,看看图像在你磁盘上的位置。

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多