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