test_httpClient.cpp 10.2 KB
Newer Older
xiongziliang committed
1
/*
xiongziliang committed
2 3
 * MIT License
 *
xiongziliang committed
4
 * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com>
xiongziliang committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 *
 * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
26 27

#include <signal.h>
28
#include <string>
29
#include <iostream>
30 31
#include "Util/MD5.h"
#include "Util/File.h"
32 33 34
#include "Util/logger.h"
#include "Util/onceToken.h"
#include "Poller/EventPoller.h"
35 36
#include "Http/HttpRequester.h"
#include "Http/HttpDownloader.h"
37 38

using namespace std;
xiongziliang committed
39 40
using namespace toolkit;
using namespace mediakit;
41

42
int main(int argc, char *argv[]) {
43
    //设置退出信号处理函数
44 45 46
    static semaphore sem;
    signal(SIGINT, [](int) { sem.post(); });// 设置退出信号

47
    //设置日志
48
    Logger::Instance().add(std::make_shared<ConsoleChannel>());
49 50
    Logger::Instance().setWriter(std::make_shared<AsyncLogWriter>());

51 52 53 54 55 56 57
    //加载证书,证书包含公钥和私钥
    SSL_Initor::Instance().loadCertificate((exeDir() + "ssl.p12").data());
    //信任某个自签名证书
    SSL_Initor::Instance().trustCertificate((exeDir() + "ssl.p12").data());
    //不忽略无效证书证书(例如自签名或过期证书)
    SSL_Initor::Instance().ignoreInvalidCertificate(false);

58 59 60 61
    ///////////////////////////////http downloader///////////////////////
    //下载器map
    map<string, HttpDownloader::Ptr> downloaderMap;
    //下载两个文件,一个是http下载,一个https下载
62 63
    auto urlList = {"http://www.baidu.com/img/baidu_resultlogo@2.png",
                    "https://www.baidu.com/img/baidu_resultlogo@2.png"};
64

65 66 67
    for (auto &url : urlList) {
        //创建下载器
        HttpDownloader::Ptr downloader(new HttpDownloader());
xiongziliang committed
68
        downloader->setOnResult([](ErrCode code, const string &errMsg, const string &filePath) {
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
            DebugL << "=====================HttpDownloader result=======================";
            //下载结果回调
            if (code == Err_success) {
                //文件下载成功
                InfoL << "download file success:" << filePath;
            } else {
                //下载失败
                WarnL << "code:" << code << " msg:" << errMsg;
            }
        });
        //断点续传功能,开启后可能会遇到416的错误(因为上次文件已经下载完全)
        downloader->startDownload(url, exeDir() + MD5(url).hexdigest() + ".jpg", true);
        //下载器必须被强引用,否则作用域一失效就会导致对象销毁
        downloaderMap.emplace(url, downloader);
    }

    ///////////////////////////////http get///////////////////////
    //创建一个Http请求器
    HttpRequester::Ptr requesterGet(new HttpRequester());
    //使用GET方式请求
    requesterGet->setMethod("GET");
    //设置http请求头,我们假设设置cookie,当然你也可以设置其他http头
    requesterGet->addHeader("Cookie", "SESSIONID=e1aa89b3-f79f-4ac6-8ae2-0cea9ae8e2d7");
    //开启请求,该api会返回当前主机外网ip等信息
    requesterGet->startRequester("http://pv.sohu.com/cityjson?ie=utf-8",//url地址
                                 [](const SockException &ex,                                 //网络相关的失败信息,如果为空就代表成功
                                    const string &status,                                    //http回复的状态码,比如说200/404
                                    const HttpClient::HttpHeader &header,                    //http回复头
                                    const string &strRecvBody) {                              //http回复body
                                     DebugL << "=====================HttpRequester GET===========================";
                                     if (ex) {
                                         //网络相关的错误
                                         WarnL << "network err:" << ex.getErrCode() << " " << ex.what();
                                     } else {
                                         //打印http回复信息
                                         _StrPrinter printer;
                                         for (auto &pr: header) {
                                             printer << pr.first << ":" << pr.second << "\r\n";
107
                                         }
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
                                         InfoL << "status:" << status << "\r\n"
                                               << "header:\r\n" << (printer << endl)
                                               << "\r\nbody:" << strRecvBody;
                                     }
                                 });

    ///////////////////////////////http post///////////////////////
    //创建一个Http请求器
    HttpRequester::Ptr requesterPost(new HttpRequester());
    //使用POST方式请求
    requesterPost->setMethod("POST");
    //设置http请求头
    requesterPost->addHeader("X-Requested-With", "XMLHttpRequest");
    requesterPost->addHeader("Origin", "http://fanyi.baidu.com");
    //设置POST参数列表
    HttpArgs args;
    args["query"] = "test";
    args["from"] = "en";
    args["to"] = "zh";
    args["transtype"] = "translang";
    args["simple_means_flag"] = "3";
    requesterPost->setBody(args.make());
    //开启请求
    requesterPost->startRequester("http://fanyi.baidu.com/langdetect",//url地址
                                  [](const SockException &ex,                          //网络相关的失败信息,如果为空就代表成功
                                     const string &status,                             //http回复的状态码,比如说200/404
                                     const HttpClient::HttpHeader &header,             //http回复头
                                     const string &strRecvBody) {                       //http回复body
                                      DebugL << "=====================HttpRequester POST==========================";
                                      if (ex) {
                                          //网络相关的错误
                                          WarnL << "network err:" << ex.getErrCode() << " " << ex.what();
                                      } else {
                                          //打印http回复信息
                                          _StrPrinter printer;
                                          for (auto &pr: header) {
                                              printer << pr.first << ":" << pr.second << "\r\n";
                                          }
                                          InfoL << "status:" << status << "\r\n"
                                                << "header:\r\n" << (printer << endl)
                                                << "\r\nbody:" << strRecvBody;
                                      }
                                  });

    ///////////////////////////////http upload///////////////////////
    //创建一个Http请求器
    HttpRequester::Ptr requesterUploader(new HttpRequester());
    //使用POST方式请求
    requesterUploader->setMethod("POST");
    //设置http请求头
    HttpArgs argsUploader;
    argsUploader["query"] = "test";
    argsUploader["from"] = "en";
    argsUploader["to"] = "zh";
    argsUploader["transtype"] = "translang";
    argsUploader["simple_means_flag"] = "3";
164

165 166 167 168 169 170
    static string boundary = "0xKhTmLbOuNdArY";
    HttpMultiFormBody::Ptr body(new HttpMultiFormBody(argsUploader, exePath(), boundary));
    requesterUploader->setBody(body);
    requesterUploader->addHeader("Content-Type", HttpMultiFormBody::multiFormContentType(boundary));
    //开启请求
    requesterUploader->startRequester("http://fanyi.baidu.com/langdetect",//url地址
171 172 173 174
                                      [](const SockException &ex,                          //网络相关的失败信息,如果为空就代表成功
                                         const string &status,                             //http回复的状态码,比如说200/404
                                         const HttpClient::HttpHeader &header,             //http回复头
                                         const string &strRecvBody) {                       //http回复body
175
                                          DebugL << "=====================HttpRequester Uploader==========================";
176 177 178 179 180 181 182 183 184 185 186 187 188 189
                                          if (ex) {
                                              //网络相关的错误
                                              WarnL << "network err:" << ex.getErrCode() << " " << ex.what();
                                          } else {
                                              //打印http回复信息
                                              _StrPrinter printer;
                                              for (auto &pr: header) {
                                                  printer << pr.first << ":" << pr.second << "\r\n";
                                              }
                                              InfoL << "status:" << status << "\r\n"
                                                    << "header:\r\n" << (printer << endl)
                                                    << "\r\nbody:" << strRecvBody;
                                          }
                                      });
190

191
    sem.wait();
192
    return 0;
193 194
}