HttpDownloader.cpp 2.11 KB
Newer Older
xiongziliang committed
1
/*
xiongziliang committed
2
 * Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved.
xiongziliang committed
3
 *
4
 * This file is part of ZLMediaKit(https://github.com/xia-chu/ZLMediaKit).
xiongziliang committed
5
 *
xiongziliang committed
6 7 8
 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
xiongziliang committed
9 10 11 12
 */

#include "HttpDownloader.h"
#include "Util/File.h"
13
#include "Util/MD5.h"
xiongziliang committed
14
using namespace toolkit;
夏楚 committed
15
using namespace std;
xiongziliang committed
16

xiongziliang committed
17
namespace mediakit {
xiongziliang committed
18 19

HttpDownloader::~HttpDownloader() {
20
    closeFile();
xiongziliang committed
21 22
}

23 24 25 26
void HttpDownloader::startDownload(const string &url, const string &file_path, bool append) {
    _file_path = file_path;
    if (_file_path.empty()) {
        _file_path = exeDir() + "HttpDownloader/" + MD5(url).hexdigest();
27
    }
28 29 30
    _save_file = File::create_file(_file_path.data(), append ? "ab" : "wb");
    if (!_save_file) {
        auto strErr = StrPrinter << "打开文件失败:" << file_path << endl;
31 32
        throw std::runtime_error(strErr);
    }
33 34
    if (append) {
        auto currentLen = ftell(_save_file);
35
        if (currentLen) {
36 37
            //最少续传一个字节,怕遇到http 416的错误
            currentLen -= 1;
38
            fseek(_save_file, -1, SEEK_CUR);
39 40 41 42
        }
        addHeader("Range", StrPrinter << "bytes=" << currentLen << "-" << endl);
    }
    setMethod("GET");
43
    sendRequest(url);
xiongziliang committed
44 45
}

46
void HttpDownloader::onResponseHeader(const string &status, const HttpHeader &headers) {
47
    if (status != "200" && status != "206") {
48
        //失败
49
        throw std::invalid_argument("bad http status: " + status);
50
    }
xiongziliang committed
51 52
}

53 54 55
void HttpDownloader::onResponseBody(const char *buf, size_t size) {
    if (_save_file) {
        fwrite(buf, size, 1, _save_file);
56
    }
xiongziliang committed
57
}
58

59
void HttpDownloader::onResponseCompleted(const SockException &ex) {
60
    closeFile();
61 62 63
    if (_on_result) {
        _on_result(ex, _file_path);
        _on_result = nullptr;
64
    }
xiongziliang committed
65 66 67
}

void HttpDownloader::closeFile() {
68 69 70 71
    if (_save_file) {
        fflush(_save_file);
        fclose(_save_file);
        _save_file = nullptr;
72
    }
xiongziliang committed
73 74
}

xiongziliang committed
75
} /* namespace mediakit */