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

查看:394
本文介绍了带有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");
}

推荐答案

通常,即使您对此一无所知,并且不需要像boost/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的安装目录"下,找到示例目录(在我的情况下为poco\poco-1.4.6p4\Net\samples\httpget\src).

Under the poco "installation directory" you find the sample directory, (in my case under poco\poco-1.4.6p4\Net\samples\httpget\src ).

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

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

如果您目前对C ++的了解不足,请去大学图书馆借阅Scott Meyers的书(有效的C ++和更有效的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;
}

该功能几乎未受影响:

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天全站免登陆