util.cpp
Go to the documentation of this file.
00001 #include "cpr/util.h"
00002 
00003 #include <cctype>
00004 #include <cstdint>
00005 #include <iomanip>
00006 #include <sstream>
00007 #include <string>
00008 #include <vector>
00009 
00010 namespace cpr {
00011 namespace util {
00012 
00013 Header parseHeader(const std::string& headers) {
00014     Header header;
00015     std::vector<std::string> lines;
00016     std::istringstream stream(headers);
00017     {
00018         std::string line;
00019         while (std::getline(stream, line, '\n')) {
00020             lines.push_back(line);
00021         }
00022     }
00023 
00024     for (auto& line : lines) {
00025         if (line.substr(0, 5) == "HTTP/") {
00026             header.clear();
00027         }
00028 
00029         if (line.length() > 0) {
00030             auto found = line.find(":");
00031             if (found != std::string::npos) {
00032                 auto value = line.substr(found + 2, line.length() - 1);
00033                 if (value.back() == '\r') {
00034                     value = value.substr(0, value.length() - 1);
00035                 }
00036                 header[line.substr(0, found)] = value;
00037             }
00038         }
00039     }
00040 
00041     return header;
00042 }
00043 
00044 std::vector<std::string> split(const std::string& to_split, char delimiter) {
00045     std::vector<std::string> tokens;
00046 
00047     std::stringstream stream(to_split);
00048     std::string item;
00049     while (std::getline(stream, item, delimiter)) {
00050         tokens.push_back(item);
00051     }
00052 
00053     return tokens;
00054 }
00055 
00056 size_t writeFunction(void* ptr, size_t size, size_t nmemb, std::string* data) {
00057     data->append((char*) ptr, size * nmemb);
00058     return size * nmemb;
00059 }
00060 
00061 std::string urlEncode(const std::string& value) {
00062     std::ostringstream escaped;
00063     escaped.fill('0');
00064     escaped << std::hex;
00065 
00066     for (auto i = value.cbegin(), n = value.cend(); i != n; ++i) {
00067         std::string::value_type c = (*i);
00068         // Keep alphanumeric and other accepted characters intact
00069         if (std::isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
00070             escaped << c;
00071             continue;
00072         }
00073         // Any other characters are percent-encoded
00074         escaped << '%' << std::setw(2) << std::int32_t((unsigned char) c);
00075     }
00076 
00077     return escaped.str();
00078 }
00079 
00080 } // namespace util
00081 } // namespace cpr


rc_visard_driver
Author(s): Heiko Hirschmueller , Christian Emmerich , Felix Ruess
autogenerated on Thu Jun 6 2019 20:43:07