[英]C++ Http Request with POCO
I'm wondering how I can do a request to a URL (eg download a picture and save it) with POCO in C++? 我想知道如何用C ++中的POCO对URL进行请求(例如下载图片并保存)?
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");
}
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 ( eg what means enable_share_from_this ... ) 通常POCO有一个非常简单的优点,即使你对它一无所知,你也不需要像boost / asio那样的中/高级C ++知识(例如,什么意思是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
). 在poco“安装目录”下,您可以找到示例目录(在我的情况下,在
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++ ) 如果您目前对C ++的理解还不够,那就去大学图书馆并借阅Scott Meyers的书籍(Effective C ++和更高效的C ++之后)
So we adapt the sample code httpget.cpp
to the minimal required. 因此,我们将示例代码
httpget.cpp
调整为最低要求。
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 希望它会有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.