C++ Http Request with POCO
Asked Answered
S

1

11

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");
}
Stygian answered 24/9, 2014 at 16:3 Comment(1)
Just an additional info, I was able to compile above code in Windows cygwin environment. First install the following cygwin packages: libpoco-devel, libpoco49. And to compile the above C++ snippet by: g++ -o snippet snippet.cpp -L/usr/lib/ -l:libPocoFoundation.dll.a -l:libPocoNet.dll.a -I/usr/include/Poco/NetOrebro
M
36

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 ... )

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).

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++ )

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

Inside the main:

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.

Hope it will help

Mameluke answered 24/9, 2014 at 21:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.