-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathHttpClient.cpp
More file actions
97 lines (74 loc) · 2.61 KB
/
HttpClient.cpp
File metadata and controls
97 lines (74 loc) · 2.61 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
68
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
#include <curl/curl.h>
#include <iostream>
#include "HttpClient.h"
static size_t writeCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
((std::string *) userp)->append((char *) contents, size * nmemb);
return size * nmemb;
}
HttpClient::HttpClient() : HttpClient(false) {}
HttpClient::HttpClient(bool debug) {
this->debug = debug;
}
void HttpClient::setCacert(std::string cacert) {
this->cacert = cacert;
}
std::string HttpClient::get(std::string url, std::string token) {
CURL *curl;
std::string readBuffer;
curl = curl_easy_init();
if (curl) {
struct curl_slist *chunk = nullptr;
chunk = curl_slist_append(chunk, ("X-Vault-Token: " + token).c_str());
// TODO: SSL verify host and peer
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
curl_easy_setopt(curl, CURLOPT_CAINFO, cacert.c_str());
if (debug) {
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
}
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK) {
std::cout << "GET " << url << " failed: " << curl_easy_strerror(res) << std::endl;
}
curl_easy_cleanup(curl);
curl_slist_free_all(chunk);
}
return readBuffer;
}
std::string HttpClient::post(std::string url, std::string token) {
return post(url,token,"");
}
std::string HttpClient::post(std::string url, std::string token, std::string value) {
CURL *curl;
CURLcode res = CURLE_SEND_ERROR;
std::string readBuffer;
curl = curl_easy_init();
if (curl) {
struct curl_slist *chunk = nullptr;
if(!token.empty()) {
chunk = curl_slist_append(chunk, ("X-Vault-Token: " + token).c_str());
}
chunk = curl_slist_append(chunk, "Accept: application/json");
chunk = curl_slist_append(chunk, "Content-Type: application/json");
// TODO: SSL verify host and peer
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, value.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
curl_easy_setopt(curl, CURLOPT_CAINFO, cacert.c_str());
if (debug) {
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
}
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
std::cout << "POST " << url << " failed: " << curl_easy_strerror(res) << std::endl;
}
curl_easy_cleanup(curl);
curl_slist_free_all(chunk);
}
return readBuffer;
}