75
|
1 #include "core/http.h"
|
|
2 #include "core/session.h"
|
|
3 #include <QByteArray>
|
|
4 #include <QMessageBox>
|
|
5 #include <curl/curl.h>
|
|
6 #include <string>
|
|
7 #include <vector>
|
|
8
|
|
9 namespace HTTP {
|
|
10
|
77
|
11 static size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userdata) {
|
75
|
12 reinterpret_cast<QByteArray*>(userdata)->append(reinterpret_cast<char*>(contents), size * nmemb);
|
|
13 return size * nmemb;
|
|
14 }
|
|
15
|
77
|
16 QByteArray Get(std::string url, std::vector<std::string> headers) {
|
75
|
17 struct curl_slist* list = NULL;
|
|
18 QByteArray userdata;
|
|
19
|
|
20 CURL* curl = curl_easy_init();
|
|
21 if (curl) {
|
77
|
22 for (const std::string& h : headers) {
|
75
|
23 list = curl_slist_append(list, h.c_str());
|
|
24 }
|
77
|
25 curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
|
|
26 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list);
|
75
|
27 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &userdata);
|
|
28 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &WriteCallback);
|
|
29 /* Use system certs... useful on Windows. */
|
|
30 curl_easy_setopt(curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA);
|
|
31 CURLcode res = curl_easy_perform(curl);
|
|
32 session.IncrementRequests();
|
|
33 curl_easy_cleanup(curl);
|
|
34 if (res != CURLE_OK) {
|
|
35 QMessageBox box(QMessageBox::Icon::Critical, "",
|
|
36 QString("curl_easy_perform(curl) failed!: ") + QString(curl_easy_strerror(res)));
|
|
37 box.exec();
|
|
38 }
|
|
39 }
|
77
|
40 return userdata;
|
75
|
41 }
|
|
42
|
77
|
43 QByteArray Post(std::string url, std::string data, std::vector<std::string> headers) {
|
|
44 struct curl_slist* list = NULL;
|
|
45 QByteArray userdata;
|
75
|
46
|
|
47 CURL* curl = curl_easy_init();
|
|
48 if (curl) {
|
|
49 for (const std::string& h : headers) {
|
|
50 list = curl_slist_append(list, h.c_str());
|
|
51 }
|
|
52 curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
|
|
53 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str());
|
|
54 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list);
|
|
55 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &userdata);
|
77
|
56 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &WriteCallback);
|
75
|
57 /* Use system certs... useful on Windows. */
|
|
58 curl_easy_setopt(curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA);
|
|
59 CURLcode res = curl_easy_perform(curl);
|
|
60 session.IncrementRequests();
|
|
61 curl_easy_cleanup(curl);
|
|
62 if (res != CURLE_OK) {
|
|
63 QMessageBox box(QMessageBox::Icon::Critical, "",
|
|
64 QString("curl_easy_perform(curl) failed!: ") + QString(curl_easy_strerror(res)));
|
|
65 box.exec();
|
|
66 }
|
|
67 }
|
77
|
68 return userdata;
|
75
|
69 }
|
|
70
|
76
|
71 } // namespace HTTP
|