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 const string &Message::get_header(const string &hdr) const
31 HeaderMap::const_iterator i=headers.find(normalize_header_name(hdr));
33 throw KeyError("Undefined header", hdr);
38 void Message::add_content(const string &d)
41 if(headers.count("Content-Type")==0)
42 set_header("Content-Type", "text/plain");
43 set_header("Content-Length", lexical_cast(content.size()));
46 void Message::set_user_data(const Variant &d)
51 unsigned Message::parse_content(const string &d)
56 HeaderMap::const_iterator i=headers.find("Content-Length");
59 unsigned needed=lexical_cast<unsigned>(i->second)-content.size();
60 unsigned len=min(needed, d.size());
62 content.append(d, 0, len);
70 i=headers.find("Transfer-Encoding");
71 if(i!=headers.end() && strcasecmp(i->second, "chunked")==0)
74 while(!complete && pos<d.size())
78 unsigned lf=d.find('\n', pos);
81 chunk_length=lexical_cast<unsigned>(strip(d.substr(pos, lf-pos)), "x");
88 unsigned len=min(chunk_length, d.size()-pos);
89 content.append(d, pos, len);
91 if((pos=d.find('\n', pos+len))!=string::npos)
103 unsigned Message::parse_headers(const string &d)
108 unsigned lf=d.find('\n', start);
110 throw InvalidParameterValue("Incomplete response");
111 if(lf==start || (d[start]=='\r' && lf==start+1))
114 unsigned colon=d.find(':', start);
116 throw InvalidParameterValue("No colon in header");
118 set_header(d.substr(start, colon-start), strip(d.substr(colon+1, lf-colon-1)));
124 string Message::str_common() const
128 for(HeaderMap::const_iterator i=headers.begin(); i!=headers.end(); ++i)
130 result+=format("%s: %s\r\n", i->first, i->second);
137 string Message::normalize_header_name(const string &hdr) const
141 for(string::iterator i=result.begin(); i!=result.end(); ++i)