编程语言
首页 > 编程语言> > C++ Poco 发起HTTP请求并获取响应

C++ Poco 发起HTTP请求并获取响应

作者:互联网

#include <Poco/Net/HTTPClientSession.h>
#include <Poco/Net/HTTPRequest.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/StreamCopier.h>
#include <Poco/URI.h>

#include <fstream>
#include <iostream>
#include <string>

bool Get(const std::string& link, const std::string& file_name) {
    // Send request
    Poco::URI uri(link);
    Poco::Net::HTTPClientSession session(uri.getHost(), uri.getPort());
    Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, uri.getPath(), Poco::Net::HTTPMessage::HTTP_1_1);
    session.sendRequest(request);
    // Recv response
    Poco::Net::HTTPResponse response;
    std::istream& recv_response = session.receiveResponse(response);
    // Response len
    int64_t total_size = response.getContentLength();
    // Write to file
    {
        std::ofstream output_file(file_name, std::ios_base::out | std::ios_base::binary);
        Poco::StreamCopier copier;
        copier.copyStream(recv_response, output_file);
        int len = output_file.tellp();
        output_file.close();
    }
    // stdout
    {
        Poco::StreamCopier copier;
        copier.copyStream(recv_response, std::cout);
    }
    return true;
}

标签:std,HTTP,C++,Poco,file,Net,include,response
来源: https://www.cnblogs.com/umichan0621/p/16495527.html