lib/webdriver/http/xhrclient.js

1// Copyright 2011 Software Freedom Conservancy. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15/** @fileoverview A XHR client. */
16
17goog.provide('webdriver.http.XhrClient');
18
19goog.require('goog.json');
20goog.require('goog.net.XmlHttp');
21goog.require('webdriver.http.Response');
22
23
24
25/**
26 * A HTTP client that sends requests using XMLHttpRequests.
27 * @param {string} url URL for the WebDriver server to send commands to.
28 * @constructor
29 * @implements {webdriver.http.Client}
30 */
31webdriver.http.XhrClient = function(url) {
32
33 /** @private {string} */
34 this.url_ = url;
35};
36
37
38/** @override */
39webdriver.http.XhrClient.prototype.send = function(request, callback) {
40 try {
41 var xhr = /** @type {!XMLHttpRequest} */ (goog.net.XmlHttp());
42 var url = this.url_ + request.path;
43 xhr.open(request.method, url, true);
44
45 xhr.onload = function() {
46 callback(null, webdriver.http.Response.fromXmlHttpRequest(xhr));
47 };
48
49 xhr.onerror = function() {
50 callback(Error([
51 'Unable to send request: ', request.method, ' ', url,
52 '\nOriginal request:\n', request
53 ].join('')));
54 };
55
56 for (var header in request.headers) {
57 xhr.setRequestHeader(header, request.headers[header] + '');
58 }
59
60 xhr.send(goog.json.serialize(request.data));
61 } catch (ex) {
62 callback(ex);
63 }
64};