3 This file is part of libmsphttp
4 Copyright © 2008 Mikkosoft Productions, Mikko Rasa
5 Distributed under the LGPL
9 #include <msp/strings/formatter.h>
10 #include <msp/strings/utils.h>
24 void Message::set_header(const string &hdr, const string &val)
26 headers[normalize_header_name(hdr)]=val;
29 bool Message::has_header(const string &hdr) const
31 return headers.count(normalize_header_name(hdr));
34 const string &Message::get_header(const string &hdr) const
36 HeaderMap::const_iterator i=headers.find(normalize_header_name(hdr));
38 throw KeyError("Undefined header", hdr);
43 void Message::add_content(const string &d)
46 if(headers.count("Content-Type")==0)
47 set_header("Content-Type", "text/plain");
48 set_header("Content-Length", lexical_cast(content.size()));
51 void Message::set_user_data(const Variant &d)
56 unsigned Message::parse_content(const string &d)
61 HeaderMap::const_iterator i=headers.find("Content-Length");
64 unsigned needed=lexical_cast<unsigned>(i->second)-content.size();
65 unsigned len=min(needed, d.size());
67 content.append(d, 0, len);
75 i=headers.find("Transfer-Encoding");
76 if(i!=headers.end() && strcasecmp(i->second, "chunked")==0)
79 while(!complete && pos<d.size())
83 unsigned lf=d.find('\n', pos);
86 chunk_length=lexical_cast<unsigned>(strip(d.substr(pos, lf-pos)), "x");
93 unsigned len=min(chunk_length, d.size()-pos);
94 content.append(d, pos, len);
96 if((pos=d.find('\n', pos+len))!=string::npos)
108 unsigned Message::parse_headers(const string &d)
113 unsigned lf=d.find('\n', start);
115 throw InvalidParameterValue("Incomplete response");
116 if(lf==start || (d[start]=='\r' && lf==start+1))
119 unsigned colon=d.find(':', start);
121 throw InvalidParameterValue("No colon in header");
123 set_header(d.substr(start, colon-start), strip(d.substr(colon+1, lf-colon-1)));
129 string Message::str_common() const
133 for(HeaderMap::const_iterator i=headers.begin(); i!=headers.end(); ++i)
135 result+=format("%s: %s\r\n", i->first, i->second);
142 string Message::normalize_header_name(const string &hdr) const
146 for(string::iterator i=result.begin(); i!=result.end(); ++i)