1 #include "HTTPRequest.hxx"
3 #include <simgear/misc/strutils.hxx>
4 #include <simgear/compiler.h>
5 #include <simgear/debug/logstream.hxx>
16 extern const int DEFAULT_HTTP_PORT;
18 Request::Request(const string& url, const string method) :
30 void Request::setUrl(const string& url)
35 string_list Request::requestHeaders() const
41 string Request::header(const std::string& name) const
46 void Request::responseStart(const string& r)
48 const int maxSplit = 2; // HTTP/1.1 nnn reason-string
49 string_list parts = strutils::split(r, NULL, maxSplit);
50 if (parts.size() != 3) {
51 SG_LOG(SG_IO, SG_WARN, "HTTP::Request: malformed response start:" << r);
52 _responseStatus = 400;
53 _responseReason = "bad HTTP response header";
57 _responseStatus = strutils::to_int(parts[1]);
58 _responseReason = parts[2];
61 void Request::responseHeader(const string& key, const string& value)
63 _responseHeaders[key] = value;
66 void Request::responseHeadersComplete()
71 void Request::gotBodyData(const char* s, int n)
76 void Request::responseComplete()
81 string Request::scheme() const
83 int firstColon = url().find(":");
85 return url().substr(0, firstColon);
88 return ""; // couldn't parse scheme
91 string Request::path() const
94 int schemeEnd = u.find("://");
96 return ""; // couldn't parse scheme
99 int hostEnd = u.find('/', schemeEnd + 3);
101 return ""; // couldn't parse host
104 int query = u.find('?', hostEnd + 1);
106 // all remainder of URL is path
107 return u.substr(hostEnd);
110 return u.substr(hostEnd, query - hostEnd);
113 string Request::host() const
115 string hp(hostAndPort());
116 int colonPos = hp.find(':');
118 return hp.substr(0, colonPos); // trim off the colon and port
120 return hp; // no port specifier
124 unsigned short Request::port() const
126 string hp(hostAndPort());
127 int colonPos = hp.find(':');
129 return (unsigned short) strutils::to_int(hp.substr(colonPos + 1));
131 return DEFAULT_HTTP_PORT;
135 string Request::hostAndPort() const
138 int schemeEnd = u.find("://");
140 return ""; // couldn't parse scheme
143 int hostEnd = u.find('/', schemeEnd + 3);
144 if (hostEnd < 0) { // all remainder of URL is host
145 return u.substr(schemeEnd + 3);
148 return u.substr(schemeEnd + 3, hostEnd - (schemeEnd + 3));
151 unsigned int Request::contentLength() const
153 HeaderDict::const_iterator it = _responseHeaders.find("content-length");
154 if (it == _responseHeaders.end()) {
158 return (unsigned int) strutils::to_int(it->second);
161 } // of namespace HTTP
163 } // of namespace simgear