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) :
33 void Request::setUrl(const string& url)
38 string_list Request::requestHeaders() const
44 string Request::header(const std::string& name) const
49 void Request::responseStart(const string& r)
51 const int maxSplit = 2; // HTTP/1.1 nnn reason-string
52 string_list parts = strutils::split(r, NULL, maxSplit);
53 if (parts.size() != 3) {
54 SG_LOG(SG_IO, SG_WARN, "HTTP::Request: malformed response start:" << r);
55 _responseStatus = 400;
56 _responseReason = "bad HTTP response header";
60 _responseStatus = strutils::to_int(parts[1]);
61 _responseReason = parts[2];
64 void Request::responseHeader(const string& key, const string& value)
66 _responseHeaders[key] = value;
69 void Request::responseHeadersComplete()
74 void Request::processBodyBytes(const char* s, int n)
76 _receivedBodyBytes += n;
80 void Request::gotBodyData(const char* s, int n)
85 void Request::responseComplete()
90 string Request::scheme() const
92 int firstColon = url().find(":");
94 return url().substr(0, firstColon);
97 return ""; // couldn't parse scheme
100 string Request::path() const
103 int schemeEnd = u.find("://");
105 return ""; // couldn't parse scheme
108 int hostEnd = u.find('/', schemeEnd + 3);
110 return ""; // couldn't parse host
113 int query = u.find('?', hostEnd + 1);
115 // all remainder of URL is path
116 return u.substr(hostEnd);
119 return u.substr(hostEnd, query - hostEnd);
122 string Request::host() const
124 string hp(hostAndPort());
125 int colonPos = hp.find(':');
127 return hp.substr(0, colonPos); // trim off the colon and port
129 return hp; // no port specifier
133 unsigned short Request::port() const
135 string hp(hostAndPort());
136 int colonPos = hp.find(':');
138 return (unsigned short) strutils::to_int(hp.substr(colonPos + 1));
140 return DEFAULT_HTTP_PORT;
144 string Request::hostAndPort() const
147 int schemeEnd = u.find("://");
149 return ""; // couldn't parse scheme
152 int hostEnd = u.find('/', schemeEnd + 3);
153 if (hostEnd < 0) { // all remainder of URL is host
154 return u.substr(schemeEnd + 3);
157 return u.substr(schemeEnd + 3, hostEnd - (schemeEnd + 3));
160 void Request::setResponseLength(unsigned int l)
165 unsigned int Request::responseLength() const
167 // if the server didn't supply a content length, use the number
168 // of bytes we actually received (so far)
169 if ((_responseLength == 0) && (_receivedBodyBytes > 0)) {
170 return _receivedBodyBytes;
173 return _responseLength;
176 void Request::setFailure(int code, const std::string& reason)
178 _responseStatus = code;
179 _responseReason = reason;
183 void Request::failed()
185 // no-op in base class
188 } // of namespace HTTP
190 } // of namespace simgear