Menu

[r224]: / trunk / boost / network / protocol / http / client.hpp  Maximize  Restore  History

Download this file

346 lines (275 with data), 14.0 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
// Copyright Dean Michael Berris 2007-2008.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef __NETWORK_PROTOCOL_HTTP_CLIENT_20070908_1_HPP__
#define __NETWORK_PROTOCOL_HTTP_CLIENT_20070908_1_HPP__
#ifndef BOOST_NETLIB_VERSION
#define BOOST_NETLIB_VERSION "0.3"
#endif
#include <boost/network/traits/ostringstream.hpp>
#include <boost/network/protocol/http/message.hpp>
#include <boost/network/protocol/http/response.hpp>
#include <boost/network/protocol/http/request.hpp>
#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/foreach.hpp>
#include <ostream>
#include <istream>
#include <string>
#include <stdexcept>
#include <map>
namespace boost { namespace network { namespace http {
template <class tag, unsigned version_major, unsigned version_minor>
class basic_client {
private:
boost::asio::io_service service_;
boost::asio::ip::tcp::resolver resolver_;
bool cache_resolved_;
bool follow_redirect_;
typedef std::pair<
boost::asio::ip::tcp::resolver::iterator,
boost::asio::ip::tcp::resolver::iterator
> resolver_iterator_pair;
typedef typename string<tag>::type string_type;
typedef std::map<string_type, resolver_iterator_pair> resolved_cache;
resolved_cache endpoint_cache_;
resolver_iterator_pair resolve(string_type const & hostname, string_type const & port) {
if (cache_resolved_) {
typename resolved_cache::iterator cached_iterator =
endpoint_cache_.find(hostname);
if (cached_iterator == endpoint_cache_.end()) {
bool inserted = false;
boost::tie(cached_iterator, inserted) =
endpoint_cache_.insert(
std::make_pair(
hostname,
std::make_pair(
resolver_.resolve(
boost::asio::ip::tcp::resolver::query(
hostname,
port,
boost::asio::ip::tcp::resolver_query::numeric_service
)
)
, boost::asio::ip::tcp::resolver::iterator()
)
)
);
};
return cached_iterator->second;
};
return std::make_pair(
resolver_.resolve(
boost::asio::ip::tcp::resolver::query(
hostname,
port,
boost::asio::ip::tcp::resolver_query::numeric_service
)
)
,
boost::asio::ip::tcp::resolver::iterator()
);
};
void init_socket(boost::asio::ip::tcp::socket & socket_, string_type const & hostname, string_type const & port) {
using boost::asio::ip::tcp;
boost::system::error_code error = boost::asio::error::host_not_found;
tcp::resolver::iterator endpoint_iterator, end;
boost::tie(endpoint_iterator, end) = resolve(hostname, port);
while (error && endpoint_iterator != end) {
socket_.close();
socket_.connect(*endpoint_iterator++, error);
}
if (error)
throw boost::system::system_error(error);
};
void create_request(boost::asio::streambuf & request_buffer, string_type const & method, basic_request<tag> request_) const {
std::ostream request_stream(&request_buffer);
request_stream
<< method << " ";
if (request_.path().empty() || request_.path()[0] != '/')
request_stream << '/';
request_stream
<< request_.path()
;
if (!request_.query().empty())
request_stream
<< '?'
<< request_.query()
;
if (!request_.anchor().empty())
request_stream
<< '#'
<< request_.anchor()
;
request_stream << " HTTP/" << version_major << '.' << version_minor << "\r\n"
<< "Host: " << request_.host() << "\r\n"
<< "Accept: */*\r\n";
headers_range<http::request>::type range = headers(request_);
BOOST_FOREACH(headers_range<http::request>::type::value_type const & header, range) {
request_stream << header.first << ": " << header.second << "\r\n";
};
range = headers(request_)["user-agent"];
if (begin(range) == end(range))
request_stream << "User-Agent: cpp-netlib/" << BOOST_NETLIB_VERSION << "\r\n";
request_stream
<< "Connection: close\r\n\r\n";
string_type body_ = body(request_);
if (!body_.empty())
request_stream << body_;
};
void send_request(boost::asio::ip::tcp::socket & socket, string_type const & method, basic_request<tag> const & request_) const {
boost::asio::streambuf request_buffer;
create_request(request_buffer, method, request_);
write(socket, request_buffer);
};
void read_status(basic_response<tag> & response_, boost::asio::ip::tcp::socket & socket, boost::asio::streambuf & response_buffer) const {
boost::asio::read_until(socket, response_buffer, "\r\n");
std::istream response_stream(&response_buffer);
string_type http_version;
unsigned int status_code;
string_type status_message;
response_stream >> http_version
>> status_code;
std::getline(response_stream, status_message);
trim_left(status_message);
trim_right_if(status_message, boost::is_space() || boost::is_any_of("\r"));
if (!response_stream || http_version.substr(0, 5) != "HTTP/")
throw std::runtime_error("Invalid response");
response_.version() = http_version;
response_.status() = status_code;
response_.status_message() = status_message;
};
void read_headers(basic_response<tag> & response_, boost::asio::ip::tcp::socket & socket, boost::asio::streambuf & response_buffer) const {
boost::asio::read_until(socket, response_buffer, "\r\n\r\n");
std::istream response_stream(&response_buffer);
string_type header_line, name;
while (std::getline(response_stream, header_line) && header_line != "\r") {
trim_right_if(header_line, boost::is_space() || boost::is_any_of("\r"));
typename string_type::size_type colon_offset;
if (header_line.size() && header_line[0] == ' ') {
assert(!name.empty());
if (name.empty())
throw std::runtime_error(
std::string("Malformed header: ")
+ header_line
);
response_
<< header(name, trim_left_copy(header_line));
} else if ((colon_offset = header_line.find_first_of(':')) != string_type::npos) {
name = header_line.substr(0, colon_offset);
response_
<< header(name, header_line.substr(colon_offset+2));
};
};
};
void read_body(basic_response<tag> & response_, boost::asio::ip::tcp::socket & socket, boost::asio::streambuf & response_buffer) const {
typename ostringstream<tag>::type body_stream;
if (response_buffer.size() > 0)
body_stream << &response_buffer;
boost::system::error_code error;
while (boost::asio::read(socket, response_buffer, boost::asio::transfer_at_least(1), error))
body_stream << &response_buffer;
if (error != boost::asio::error::eof)
throw boost::system::system_error(error);
response_ << body(body_stream.str());
};
response const sync_request_skeleton(basic_request<tag> const & request_, string_type method, bool get_body) {
using boost::asio::ip::tcp;
basic_request<tag> request_copy(request_);
basic_response<tag> response_;
do {
tcp::socket socket(service_);
init_socket(socket, request_copy.host(), boost::lexical_cast<string_type>(request_copy.port()));
send_request(socket, method, request_copy);
response_ = basic_response<tag>();
response_ << source(request_copy.host());
boost::asio::streambuf response_buffer;
read_status(response_, socket, response_buffer);
read_headers(response_, socket, response_buffer);
if (get_body)
read_body(response_, socket, response_buffer);
if (follow_redirect_) {
uint16_t status = response_.status();
if (status >= 300 && status <= 307) {
headers_range<http::request>::type location_range = headers(response_)["Location"];
range_iterator<headers_range<http::request>::type>::type location_header = begin(location_range);
if (location_header != end(location_range)) {
request_copy.uri(location_header->second);
} else throw std::runtime_error("Location header not defined in redirect response.");
} else break;
} else break;
} while(true);
return response_;
};
public:
struct cache_resolved_type { };
static cache_resolved_type cache_resolved() {
return cache_resolved_type();
};
struct follow_redirect_type { };
static follow_redirect_type follow_redirects() {
return follow_redirect_type();
};
static follow_redirect_type follow_redirect() {
return follow_redirect_type();
};
basic_client()
: service_(), resolver_(service_), cache_resolved_(false), follow_redirect_(false)
{};
explicit basic_client(cache_resolved_type (*)())
: service_(), resolver_(service_), cache_resolved_(true), follow_redirect_(false)
{};
explicit basic_client(follow_redirect_type (*)())
: service_(), resolver_(service_), cache_resolved_(false), follow_redirect_(true)
{};
basic_client(cache_resolved_type (*)(), follow_redirect_type (*)())
: service_(), resolver_(service_), cache_resolved_(true), follow_redirect_(true)
{};
void clear_resolved_cache() {
endpoint_cache_.clear();
}
response const head (basic_request<tag> const & request_) {
return sync_request_skeleton(request_, "HEAD", false);
};
response const get (basic_request<tag> const & request_) {
return sync_request_skeleton(request_, "GET", true);
};
response const post (basic_request<tag> const & request_) {
return sync_request_skeleton(request_, "POST", true);
};
response const post (basic_request<tag> const & request_, string_type const & content_type, string_type const & body_) {
basic_request<tag> request_copy = request_;
request_copy << body(body_)
<< header("Content-Type", content_type)
<< header("Content-Length", boost::lexical_cast<string_type>(body_.size()));
return post(request_copy);
};
response const post (basic_request<tag> const & request_, string_type const & body_) {
return post(request_, "x-application/octet-stream", body_);
};
response const put (basic_request<tag> const & request_) {
return sync_request_skeleton(request_, "PUT", true);
};
response const put (basic_request<tag> const & request_, string_type const & body_) {
return put(request_, "x-application/octet-stream", body_);
};
response const put (basic_request<tag> const & request_, string_type const & content_type, string_type const & body_) {
basic_request<tag> request_copy = request_;
request_copy << body(body_)
<< header("Content-Type", content_type)
<< header("Content-Length", boost::lexical_cast<string_type>(body_.size()));
return put(request_copy);
};
response const delete_ (basic_request<tag> const & request_) {
return sync_request_skeleton(request_, "DELETE", true);
};
};
typedef basic_client<tags::http, 1, 0> client;
} // namespace http
} // namespace network
} // namespace boost
#endif // __NETWORK_PROTOCOL_HTTP_CLIENT_20070908_1_HPP__