/[projects]/smsdaemon/HttpClient.cpp
ViewVC logotype

Annotation of /smsdaemon/HttpClient.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 592 - (hide annotations) (download)
Fri Feb 19 08:47:31 2010 UTC (14 years, 3 months ago) by torben
File size: 1559 byte(s)
be nicer to std::vector (we might save a expansion operation or two)
1 torben 193 #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 torben 196 for (unsigned i=0; i<url.size(); i++)
15     {
16 torben 193 char ch = url.at(i);
17     if (isalnum(ch))
18     ss << ch;
19     else
20 torben 195 ss << "%" << std::setw(2) << std::hex << std::setfill('0') <<(int) ch;
21 torben 193 }
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 torben 592 vec->reserve( vec->size() + total); //allow vector to do a preallocation if necessary
34    
35 torben 193 int i;
36 torben 196 for (i=0; i<total; i++)
37     {
38     vec->push_back( bytes[i] );
39     }
40 torben 193 return i;
41     }
42    
43     std::vector<char> Get(std::string url)
44     {
45     std::vector<char> buf;
46     char errmsg[128] = "";
47    
48     CURL* curl = curl_easy_init();
49     if (curl == 0)
50     throw httpexception("could not init CURL");
51    
52     curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
53    
54 torben 196 curl_easy_setopt(curl, CURLOPT_URL, url.c_str() );
55     curl_easy_setopt(curl, CURLOPT_FAILONERROR,1);
56     curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunction);
57 torben 193 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buf);
58    
59 torben 196 int res = curl_easy_perform(curl);
60     curl_easy_cleanup(curl);
61 torben 193
62     if (res != 0)
63     throw httpexception(errmsg);
64    
65    
66    
67     return buf;
68     }
69    
70     std::string GetString(std::string url)
71     {
72     std::vector<char> buf = Get(url);
73     buf.push_back(0);
74     return std::string(&buf[0]);
75     }
76     }

  ViewVC Help
Powered by ViewVC 1.1.20