HttpClient.h 9.89 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.
 */
xiongziliang committed
26 27 28 29

#ifndef Http_HttpClient_h
#define Http_HttpClient_h

30
#include <stdio.h>
xiongziliang committed
31 32 33 34
#include <string.h>
#include <functional>
#include <memory>
#include "Util/util.h"
xiongziliang committed
35
#include "Util/mini.h"
xiongziliang committed
36
#include "Network/TcpClient.h"
xiongziliang committed
37
#include "Common/Parser.h"
38
#include "HttpRequestSplitter.h"
39
#include "HttpCookie.h"
40
#include "HttpChunkedSplitter.h"
xiongziliang committed
41
#include "strCoding.h"
xiongziliang committed
42 43

using namespace std;
xiongziliang committed
44
using namespace toolkit;
xiongziliang committed
45

xiongziliang committed
46
namespace mediakit {
xiongziliang committed
47

xiongziliang committed
48
class HttpArgs : public map<string, variant, StrCaseCompare>  {
xiongziliang committed
49 50 51 52 53 54 55 56
public:
    HttpArgs(){}
    virtual ~HttpArgs(){}
    string make() const {
        string ret;
        for(auto &pr : *this){
            ret.append(pr.first);
            ret.append("=");
xiongziliang committed
57
            ret.append(strCoding::UrlEncode(pr.second));
xiongziliang committed
58 59 60 61 62 63 64 65
            ret.append("&");
        }
        if(ret.size()){
            ret.pop_back();
        }
        return ret;
    }
};
66 67 68 69 70 71 72 73 74 75 76

class HttpBody{
public:
    typedef std::shared_ptr<HttpBody> Ptr;
    HttpBody(){}
    virtual ~HttpBody(){}
    //剩余数据大小
    virtual uint64_t remainSize() = 0;
    virtual Buffer::Ptr readData() = 0;
};

77
class HttpStringBody : public HttpBody{
78
public:
79 80
    typedef std::shared_ptr<HttpStringBody> Ptr;
    HttpStringBody(const string &str){
81 82
        _str = str;
    }
83
    virtual ~HttpStringBody(){}
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

    uint64_t remainSize() override {
        return _str.size();
    }
    Buffer::Ptr readData() override {
        auto ret = std::make_shared<BufferString>(_str);
        _str.clear();
        return ret;
    }
private:
    mutable string _str;
};


class HttpMultiFormBody : public HttpBody {
public:
    typedef std::shared_ptr<HttpMultiFormBody> Ptr;
xiongziliang committed
101 102
    template<typename MapType>
    HttpMultiFormBody(const MapType &args,const string &filePath,const string &boundary,uint32_t sliceSize = 4 * 1024){
103 104 105 106 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
        _fp = fopen(filePath.data(),"rb");
        if(!_fp){
            throw std::invalid_argument(StrPrinter << "打开文件失败:" << filePath << " " << get_uv_errmsg());
        }
        auto fileName = filePath;
        auto pos = filePath.rfind('/');
        if(pos != string::npos){
            fileName = filePath.substr(pos + 1);
        }
        _bodyPrefix = multiFormBodyPrefix(args,boundary,fileName);
        _bodySuffix = multiFormBodySuffix(boundary);
        _totalSize =  _bodyPrefix.size() + _bodySuffix.size() + fileSize(_fp);
        _sliceSize = sliceSize;
    }
    virtual ~HttpMultiFormBody(){
        fclose(_fp);
    }

    uint64_t remainSize() override {
        return _totalSize - _offset;
    }

    Buffer::Ptr readData() override{
        if(_bodyPrefix.size()){
            auto ret = std::make_shared<BufferString>(_bodyPrefix);
            _offset += _bodyPrefix.size();
            _bodyPrefix.clear();
            return ret;
        }

        if(0 == feof(_fp)){
            auto ret = std::make_shared<BufferRaw>(_sliceSize);
            //读文件
            int size;
            do{
                size = fread(ret->data(),1,_sliceSize,_fp);
            }while(-1 == size && UV_EINTR == get_uv_error(false));

            if(size == -1){
                _offset = _totalSize;
                WarnL << "fread failed:" << get_uv_errmsg();
                return nullptr;
            }
            _offset += size;
            ret->setSize(size);
            return ret;
        }

        if(_bodySuffix.size()){
            auto ret = std::make_shared<BufferString>(_bodySuffix);
            _offset = _totalSize;
            _bodySuffix.clear();
            return ret;
        }

        return nullptr;
    }

public:
xiongziliang committed
162 163
    template<typename MapType>
    static string multiFormBodyPrefix(const MapType &args,const string &boundary,const string &fileName){
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
        string MPboundary = string("--") + boundary;
        _StrPrinter body;
        for(auto &pr : args){
            body << MPboundary << "\r\n";
            body << "Content-Disposition: form-data; name=\"" << pr.first << "\"\r\n\r\n";
            body << pr.second << "\r\n";
        }
        body << MPboundary << "\r\n";
        body << "Content-Disposition: form-data; name=\"" << "file" << "\";filename=\"" << fileName << "\"\r\n";
        body << "Content-Type: application/octet-stream\r\n\r\n" ;
        return body;
    }
    static string multiFormBodySuffix(const string &boundary){
        string MPboundary = string("--") + boundary;
        string endMPboundary = MPboundary + "--";
        _StrPrinter body;
        body << "\r\n" << endMPboundary;
        return body;
    }

    static uint64_t fileSize(FILE *fp) {
        auto current = ftell(fp);
        fseek(fp,0L,SEEK_END); /* 定位到文件末尾 */
        auto end  = ftell(fp); /* 得到文件大小 */
        fseek(fp,current,SEEK_SET);
        return end - current;
    }

    static string multiFormContentType(const string &boundary){
        return StrPrinter << "multipart/form-data; boundary=" << boundary;
    }
private:
    FILE *_fp;
    string _bodyPrefix;
    string _bodySuffix;
    uint64_t _offset = 0;
    uint64_t _totalSize;
    uint32_t _sliceSize;
};



206
class HttpClient : public TcpClient , public HttpRequestSplitter
xiongziliang committed
207 208 209 210 211 212
{
public:
    typedef StrCaseMap HttpHeader;
    typedef std::shared_ptr<HttpClient> Ptr;
    HttpClient();
    virtual ~HttpClient();
xiongziliang committed
213
    virtual void sendRequest(const string &url,float fTimeOutSec);
214 215

    virtual void clear(){
xiongziliang committed
216
        _header.clear();
217
        _body.reset();
xiongziliang committed
218 219 220
        _method.clear();
        _path.clear();
        _parser.Clear();
221 222 223 224 225
        _recvedBodySize = 0;
        _totalBodySize = 0;
        _aliveTicker.resetTime();
        _chunkedSplitter.reset();
        HttpRequestSplitter::reset();
xiongziliang committed
226
    }
227

xiongziliang committed
228 229 230 231
    void setMethod(const string &method){
        _method = method;
    }
    void setHeader(const HttpHeader &header){
xzl committed
232
        _header = header;
xiongziliang committed
233
    }
234 235 236 237 238 239 240
    HttpClient & addHeader(const string &key,const string &val,bool force = false){
        if(!force){
            _header.emplace(key,val);
        }else{
            _header[key] = val;
        }
        return *this;
xiongziliang committed
241 242
    }
    void setBody(const string &body){
243
        _body.reset(new HttpStringBody(body));
244 245
    }
    void setBody(const HttpBody::Ptr &body){
xiongziliang committed
246 247
        _body = body;
    }
xiongziliang committed
248
    const string &responseStatus() const{
xiongziliang committed
249 250
        return _parser.Url();
    }
xiongziliang committed
251
    const HttpHeader &responseHeader() const{
xiongziliang committed
252 253
        return _parser.getValues();
    }
xiongziliang committed
254 255 256
    const Parser& response() const{
        return _parser;
    }
257 258 259 260

    const string &getUrl() const{
        return _url;
    }
xiongziliang committed
261
protected:
262 263 264 265
    /**
     * 收到http回复头
     * @param status 状态码,譬如:200 OK
     * @param headers http头
266 267
     * @return 返回后续content的长度;-1:后续数据全是content;>=0:固定长度content
     *          需要指出的是,在http头中带有Content-Length字段时,该返回值无效
268
     */
269
    virtual int64_t onResponseHeader(const string &status,const HttpHeader &headers){
xiongziliang committed
270
        DebugL << status;
271 272
        //无Content-Length字段时默认后面全是content
        return -1;
xiongziliang committed
273
    };
274 275 276 277 278 279 280 281

    /**
     * 收到http conten数据
     * @param buf 数据指针
     * @param size 数据大小
     * @param recvedSize 已收数据大小(包含本次数据大小),当其等于totalSize时将触发onResponseCompleted回调
     * @param totalSize 总数据大小
     */
282
    virtual void onResponseBody(const char *buf,int64_t size,int64_t recvedSize,int64_t totalSize){
xiongziliang committed
283 284
        DebugL << size << " " <<  recvedSize << " " << totalSize;
    };
285 286

    /**
xiongziliang committed
287
     * 接收http回复完毕,
288
     */
289
    virtual void onResponseCompleted(){
xiongziliang committed
290 291
    	DebugL;
    }
292 293 294 295 296

    /**
     * http链接断开回调
     * @param ex 断开原因
     */
xiongziliang committed
297
    virtual void onDisconnect(const SockException &ex){}
298

299 300 301 302 303 304 305 306
    /**
     * 重定向事件
     * @param url 重定向url
     * @param temporary 是否为临时重定向
     * @return 是否继续
     */
    virtual bool onRedirectUrl(const string &url,bool temporary){ return true;};

307 308 309
    //HttpRequestSplitter override
    int64_t onRecvHeader(const char *data,uint64_t len) override ;
    void onRecvContent(const char *data,uint64_t len) override;
310
protected:
xiongziliang committed
311
    virtual void onConnect(const SockException &ex) override;
312
    virtual void onRecv(const Buffer::Ptr &pBuf) override;
xiongziliang committed
313
    virtual void onErr(const SockException &ex) override;
xiongziliang committed
314
    virtual void onFlush() override;
315
    virtual void onManager() override;
316
private:
317
    void onResponseCompleted_l();
318
    void checkCookie(HttpHeader &headers );
319 320 321
protected:
    bool _isHttps;
private:
322
    string _url;
xiongziliang committed
323
    HttpHeader _header;
324
    HttpBody::Ptr _body;
xiongziliang committed
325 326 327
    string _method;
    string _path;
    //recv
328 329
    int64_t _recvedBodySize;
    int64_t _totalBodySize;
xiongziliang committed
330 331
    Parser _parser;
    string _lastHost;
332 333
    Ticker _aliveTicker;
    float _fTimeOutSec = 0;
334
    std::shared_ptr<HttpChunkedSplitter> _chunkedSplitter;
xiongziliang committed
335 336
};

xiongziliang committed
337
} /* namespace mediakit */
xiongziliang committed
338 339

#endif /* Http_HttpClient_h */