1 |
#include "HttpClient.h" |
2 |
#include "Exceptions.h" |
3 |
|
4 |
#include <iomanip> |
5 |
#include <sstream> |
6 |
#include <curl/curl.h> |
7 |
|
8 |
namespace HttpClient |
9 |
{ |
10 |
|
11 |
std::string UrlEncode(std::string url) |
12 |
{ |
13 |
std::ostringstream ss; |
14 |
for (unsigned i=0; i<url.size(); i++) |
15 |
{ |
16 |
char ch = url.at(i); |
17 |
if (isalnum(ch)) |
18 |
ss << ch; |
19 |
else |
20 |
ss << "%" << std::setw(2) << std::hex << std::setfill('0') <<(int) ch; |
21 |
} |
22 |
return ss.str(); |
23 |
} |
24 |
|
25 |
|
26 |
size_t writefunction( void *ptr, size_t size, size_t nmemb, void *stream) |
27 |
{ |
28 |
int total = size * nmemb; |
29 |
|
30 |
char* bytes = reinterpret_cast<char*>(ptr); |
31 |
std::vector<char>* vec = reinterpret_cast< std::vector<char>* >(stream); |
32 |
|
33 |
int i; |
34 |
for (i=0; i<total; i++) |
35 |
{ |
36 |
vec->push_back( bytes[i] ); |
37 |
} |
38 |
return i; |
39 |
} |
40 |
|
41 |
std::vector<char> Get(std::string url) |
42 |
{ |
43 |
std::vector<char> buf; |
44 |
char errmsg[128] = ""; |
45 |
|
46 |
CURL* curl = curl_easy_init(); |
47 |
if (curl == 0) |
48 |
throw httpexception("could not init CURL"); |
49 |
|
50 |
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg); |
51 |
|
52 |
curl_easy_setopt(curl, CURLOPT_URL, url.c_str() ); |
53 |
curl_easy_setopt(curl, CURLOPT_FAILONERROR,1); |
54 |
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunction); |
55 |
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buf); |
56 |
|
57 |
int res = curl_easy_perform(curl); |
58 |
curl_easy_cleanup(curl); |
59 |
|
60 |
if (res != 0) |
61 |
throw httpexception(errmsg); |
62 |
|
63 |
|
64 |
|
65 |
return buf; |
66 |
} |
67 |
|
68 |
std::string GetString(std::string url) |
69 |
{ |
70 |
std::vector<char> buf = Get(url); |
71 |
buf.push_back(0); |
72 |
return std::string(&buf[0]); |
73 |
} |
74 |
} |