使用POCO发送HTTP(S)请求

POCO GitHub地址https://github.com/pocoproject/poco

http_example.cpp

#include <iostream>
#include <Poco/URI.h>
#include <Poco/StreamCopier.h>
#include <Poco/Net/HTTPClientSession.h>
#include <Poco/Net/HTTPRequest.h>
#include <Poco/Net/HTMLForm.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/Net/NetException.h>
using namespace Poco;
using namespace Poco::Net;
void getExample()
{
    try
    {
        URI uri("http://api.eyekey.com/face/Check/checking?app_id=f89ae61fd63d4a63842277e9144a6bd2&app_key=af1cd33549c54b27ae24aeb041865da2&url=http%3A%2F%2Fpicview01.baomihua.com%2Fphotos%2F20120713%2Fm_14_634778197959062500_40614445.jpg");
        HTTPClientSession session(uri.getHost(), uri.getPort());
        HTTPRequest request(HTTPRequest::HTTP_GET, uri.getPathAndQuery());
        session.sendRequest(request);
        HTTPResponse response;
        std::istream &is = session.receiveResponse(response);
        const HTTPResponse::HTTPStatus &status = response.getStatus();
        if (HTTPResponse::HTTPStatus::HTTP_OK == status)
        {
            std::string result;
            StreamCopier::copyToString(is, result);
            std::cout << result << std::endl;
        }
        else
            std::cout << status << std::endl;
    }
    catch (const NetException &ex)
    {
        std::cerr << "ex: " << ex.displayText() << std::endl;
    }
}
void postExample()
{
    try
    {
        URI uri("http://api.eyekey.com/face/Check/checking");
        HTTPClientSession session(uri.getHost(), uri.getPort());
        HTMLForm form;
        form.add("app_id", "f89ae61fd63d4a63842277e9144a6bd2");
        form.add("app_key", "af1cd33549c54b27ae24aeb041865da2");
        form.add("url", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1535455294084&di=8ca75c2b8817900345c35dbe0d1940a5&imgtype=0&src=http%3A%2F%2Fa2.att.hudong.com%2F50%2F67%2F01300533963892135071679109235.png");
        HTTPRequest request(HTTPRequest::HTTP_POST, uri.getPath(), HTTPRequest::HTTP_1_1);
        form.prepareSubmit(request);
        form.write(session.sendRequest(request));
        HTTPResponse response;
        std::istream &is = session.receiveResponse(response);
        const HTTPResponse::HTTPStatus &status = response.getStatus();
        if (HTTPResponse::HTTPStatus::HTTP_OK == status)
        {
            std::string result;
            StreamCopier::copyToString(is, result);
            std::cout << result << std::endl;
        }
        else
            std::cout << status << std::endl;
    }
    catch (const NetException &ex)
    {
        std::cerr << "ex: " << ex.displayText() << std::endl;
    }
}
int main()
{
    getExample();
    std::cout << std::endl;
    postExample();
    std::cout << std::endl;
    std::system("pause");
    return 0;
}

https_example.cpp

#include <iostream>
#include <Poco/URI.h>
#include <Poco/StreamCopier.h>
#include <Poco/Net/SSLManager.h>
#include <Poco/Net/AcceptCertificateHandler.h>
#include <Poco/Net/Context.h>
#include <Poco/Net/HTTPSClientSession.h>
#include <Poco/Net/HTTPRequest.h>
#include <Poco/Net/HTMLForm.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/Net/NetException.h>
using namespace std;
using namespace Poco;
using namespace Poco::Net;
void getExample()
{
    try
    {
        SSLManager::InvalidCertificateHandlerPtr handlerPtr(new AcceptCertificateHandler(false));
        Context::Ptr context = new Context(Context::CLIENT_USE, "");
        SSLManager::instance().initializeClient(nullptr, handlerPtr, context);
        HTTPSClientSession session(context);
        URI uri("https://api.eyekey.com/face/Check/checking?app_id=f89ae61fd63d4a63842277e9144a6bd2&app_key=af1cd33549c54b27ae24aeb041865da2&url=http%3A%2F%2Fpicview01.baomihua.com%2Fphotos%2F20120713%2Fm_14_634778197959062500_40614445.jpg");
        session.setHost(uri.getHost());
        session.setPort(uri.getPort());
        HTTPRequest request(HTTPRequest::HTTP_GET, uri.getPathAndQuery());
        session.sendRequest(request);
        HTTPResponse response;
        istream &is = session.receiveResponse(response);
        const HTTPResponse::HTTPStatus &status = response.getStatus();
        if (HTTPResponse::HTTPStatus::HTTP_OK == status)
        {
            StreamCopier::copyStream(is, cout);
            cout << endl;
        }
        else
            cout << status << endl;
    }
    catch (const NetException &ex)
    {
        cerr << ex.displayText() << endl;
    }
}
void postExample()
{
    try
    {
        SSLManager::InvalidCertificateHandlerPtr handlerPtr(new AcceptCertificateHandler(false));
        Context::Ptr context = new Context(Context::CLIENT_USE, "");
        SSLManager::instance().initializeClient(nullptr, handlerPtr, context);
        HTTPSClientSession session(context);
        URI uri("https://api.eyekey.com/face/Check/checking");
        session.setHost(uri.getHost());
        session.setPort(uri.getPort());
        HTTPRequest request(HTTPRequest::HTTP_POST, uri.getPath());
        HTMLForm form;
        form.set("app_id", "f89ae61fd63d4a63842277e9144a6bd2");
        form.set("app_key", "af1cd33549c54b27ae24aeb041865da2");
        form.set("url", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1535455294084&di=8ca75c2b8817900345c35dbe0d1940a5&imgtype=0&src=http%3A%2F%2Fa2.att.hudong.com%2F50%2F67%2F01300533963892135071679109235.png");
        form.prepareSubmit(request);
        form.write(session.sendRequest(request));
        HTTPResponse response;
        istream &is = session.receiveResponse(response);
        const HTTPResponse::HTTPStatus &status = response.getStatus();
        if (HTTPResponse::HTTPStatus::HTTP_OK == status)
        {
            string result;
            StreamCopier::copyToString(is, result);
            cout << result << endl;
        }
        else
            cout << status << endl;
    }
    catch (const NetException &ex)
    {
        cerr << ex.displayText() << endl;
    }
}
int main()
{
    getExample();
    cout << endl;
    postExample();
    cout << endl;
    system("pause");
    return 0;
}

原文地址:https://www.cnblogs.com/buyishi/p/9519778.html

时间: 2024-08-30 13:53:17

使用POCO发送HTTP(S)请求的相关文章

调用webapi 错误:使用 HTTP 谓词 POST 向虚拟目录发送了一个请求,而默认文档是不支持 GET 或 HEAD 以外的 HTTP 谓词的静态文件。的解决方案

第一次调用webapi出错如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>IIS 7.5 详细错误 - 4

浏览器下载文件时一共发送2次请求,如何把“下载次数”只记录为1次?

最近,个人官网实现了PDF下载功能,出于统计的考虑,增加了"下载次数"download_count这个字段. 但是,我今天突然发现,每次下载download_count都直接+2了.如果服务器发生这种事,还有一定的可能,本地就我一个人下载,怎么可能下载2次.于是,打开了log4j的debug模式,果然执行了2次更新请求. @RequestMapping(value = "/download/pdf") public void downloadPdf(@Request

[NIO]用dawn发送接收HTTP请求

HTTP协议的下层使用的是tcp,所以我们建立一个tcp连接就能发送接收http请求.dawn底层使用了nio,但是经过dawn的封装之后,我们在编写代码的时候,就和使用普通的阻塞式socket一样 ,不需要关注nio的api.可以把我们的精力放在业务逻辑的处理上.举例如下,下例的功能就是取回baidu首页: package zhmt.dawn.nio; import java.nio.charset.Charset; import zhmt.dawn.nio.buffer.ScalableDi

解决连接vcenter (客户端无法向服务器发送完整的请求。(基础连接已经关闭:发送时发生错误。)) 问题

vCenter版本 5.5 vCenter 安装在server 2008 r2上面,今天补丁一打,重启后就无法连接vcenter了,起初以为是补丁的问题导致vcenter工作不正常,卸载了补丁依旧无法正常连接. 报未知连接错误,(客户端无法向服务器发送完整的请求.(基础连接已经关闭:发送时发生错误.)) 服务里面 vmware Virtualcenter server 服务启动不了. 倒腾了很久,, 很久   ,,    重装vcenter server 5.5的时候提示 vcenter 443

如果调用ASP.NET Web API不能发送PUT/DELETE请求怎么办?

小分享:我有几张阿里云优惠券,用券购买或者升级阿里云相应产品最多可以优惠五折!领券地址:https://promotion.aliyun.com/ntms/act/ambassador/sharetouser.html?userCode=ohmepe03 理想的RESTful Web API采用面向资源的架构,并使用请求的HTTP方法表示针对目标资源的操作类型.但是理想和现实是有距离的,虽然HTTP协议提供了一系列原生的HTTP方法,但是在具体的网络环境中,很多是不支持的.比如有的浏览器只能发送

关于页面上一次点击,发送多次请求的问题

今天在实现功能的时候发现了一个问题, 在做一个导入的时候,第几次点击导入按钮,就会发送几次请求到后台的问题 页面标签: <a href="javascript:void(0);"  class="dowload" onclick="contributionStatis_setting.exportExcel();"> js 代码(问题代码): /**         * 导出         */        exportExcel

php CURL 发送get,post请求

// 发送一个get请求 $url 发送地址    function get($url)    {        //初始化操作        $curl = curl_init($url);        //设置请求参数        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//设置结果的转换        curl_setopt($curl, CURLOPT_TIMEOUT, 10);//设置超时时间        // 发送请求    

使用python的requests 发送multipart/form-data 请求

网上关于使用python 的发送multipart/form-data的方法,多半是采用 ulrlib2 的模拟post方法,如下: import urllib2 boundary='-------------------------7df3069603d6' data=[] data.append('--%s' % boundary) data.append('Content-Disposition: form-data; name="app_id"\r\n') data.appen

HP发送HTTP POST请求 返回结果

HP发送HTTP POST请求 返回结果 <?php $srv_ip = '192.168.10.188';//你的目标服务地址或频道.$srv_port = 80;$url = '/demo/test_query_string.php'; //接收你post的URL具体地址 $fp = '';$resp_str = '';$errno = 0;$errstr = '';$timeout = 10;$post_str = "username=demo&str=aaaa";