带有 POCO 的 C++ Http 请求 [英] C++ Http Request with POCO

查看:24
本文介绍了带有 POCO 的 C++ Http 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm wondering how I can do a request to a URL (e.g. download a picture and save it) with POCO in C++?

到目前为止我得到了这个小代码

I got this little code so far

#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");
}

推荐答案

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

Normally POCO has a great advantage to be very simple even when you know nothing about it and you do not need middle/advance C++ knowledge like you need for boost/asio ( e.g what means enable_share_from_this ... )

在 poco安装目录"下,您可以找到示例目录(在我的例子中是在 pocopoco-1.4.6p4Netsampleshttpgetsrc 下).

Under the poco "installation directory" you find the sample directory, (in my case under pocopoco-1.4.6p4Netsampleshttpgetsrc ).

在线帮助浏览也简单快捷(例如浏览类).

On-line help browsing is also easy and fast (for example browsing classes).

如果你目前对 C++ 的理解还不够,去大学图书馆借 Scott Meyers 的书(Effective C++ and after More Effective C++)

If your understanding of C++ in not enough at the present time go to the university library and borrow Scott Meyers books (Effective C++ and after More effective C++ )

因此我们将示例代码 httpget.cpp 调整到最低要求.

So we adapt the sample code httpget.cpp to the minimal required.

主要内容:

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;
}

而且功能几乎没有受到影响:

and the function almost untouched:

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;
    }
}

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

I let you arrange things for you and see where the image lands on your disk.

希望能帮到你

这篇关于带有 POCO 的 C++ Http 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆