-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttputils.cpp
More file actions
67 lines (55 loc) · 1.97 KB
/
httputils.cpp
File metadata and controls
67 lines (55 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#define CPPHTTPLIB_OPENSSL_SUPPORT
#include "httputils.h"
#include "httplib.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include <map>
ApiResponse postSse(const std::string& domain, const std::string& uri, const httplib::Headers& headers, const std::string& body, StreamConsumer consumer) {
httplib::Client cli(domain);
cli.enable_server_certificate_verification(false);
auto res = cli.Post(uri, headers, body, "application/json; charset=utf-8");
if (res) {
std::string contentType = res->get_header_value("Content-Type");
if (res->status == 200) {
if (contentType.find("text/event-stream") != std::string::npos) {
// TODO c++ 实现实时流式比较复杂,这里采用模拟实现(响应结束后处理)
std::istringstream stream(res->body);
std::string line;
while (std::getline(stream, line)) {
if (line.find("data:") == 0) {
std::string data = line.substr(5);
if (data != "" && data != "[DONE]") {
consumer(data);
}
}
}
}
}
return { res->status, res->body, res->headers, contentType };
}
throw std::runtime_error("Request failed.");
}
ApiResponse postJson(const std::string& domain, const std::string& uri, const httplib::Headers& headers, const std::string& body) {
httplib::Client cli(domain);
cli.enable_server_certificate_verification(false);
auto res = cli.Post(uri, headers, body, "application/json; charset=utf-8");
if (res) {
std::string contentType = res->get_header_value("Content-Type");
return { res->status, res->body, res->headers, contentType };
}
throw std::runtime_error("Request failed.");
}
void download(const std::string& domain, const std::string& uri, const std::string& save_path) {
httplib::Client cli(domain);
cli.enable_server_certificate_verification(false);
auto res = cli.Get(uri);
if (res && res->status == 200) {
std::ofstream out(save_path, std::ios::binary);
out << res->body;
out.close();
}
else {
throw std::runtime_error("Request failed or file cannot be saved.");
}
}