Google APIs Client Library for C++
HttpRequest Class Reference

Denotes an HTTP request to be sent to an HTTP server. More...

#include "client/transport/http_request.h"

+ Inheritance diagram for HttpRequest:

List of all members.

Public Types

typedef StringPiece HttpMethod
 Methods are just a free-form StringPiece typedefed to clarify the API.

Public Member Functions

virtual ~HttpRequest ()
 User-Agent.
void DestroyWhenDone ()
 A safer destructor for asynchronous requests.
virtual void Clear ()
 Clears the request data, but not the options.
HttpRequestOptionsmutable_options ()
 Gets a mutable options instance to configure instance-specific options.
const HttpRequestOptionsoptions () const
 Gets request options.
const HttpRequestStatestate () const
 Gets request state instance containing additional attribute values.
HttpResponseresponse () const
 Returns the object managing the request's response.
const string & url () const
 Returns the URL that this request will invoke when executed.
void set_url (const string &url)
 Sets the URL to invoke when the request is executed.
void set_content_type (const StringPiece &type)
 Adds a 'Content-Type' header with the given value.
DataReadercontent_reader () const
 Returns the content_reader specifying this requests's message body.
void set_content_reader (DataReader *reader)
 Specifies the requests message body using a DataReader.
void RemoveHeader (const StringPiece &name)
 Removes the named header, if it exists.
void AddHeader (const StringPiece &name, const StringPiece &value)
 Adds a header, or replaces its value if it already exists.
const string * FindHeaderValue (const StringPiece &name) const
 Get the value of the named header.
const HttpHeaderMapheaders () const
 Get all the headers explicitly added to the request.
HttpMethod http_method () const
 Get the HTTP method for the request.
void WillNotExecute (util::Status status, HttpRequestCallback *callback=NULL)
 Indicate that the method will never Execute.
util::Status Execute ()
 Synchronously send the request to the designated URL and wait for the response.
void ExecuteAsync (HttpRequestCallback *callback)
 Asynchronously send the request to the designated URL then continue this thread while the server is processing the request.
void set_credential (AuthorizationCredential *cred)
 Sets the authorization credential.
AuthorizationCredentialcredential ()
 Returns the authorization credential.
HttpRequestStatemutable_state ()
 Returns mutable state.
util::Status PrepareToReuse ()
 Prepares the request instance so that it can be reused again.
util::Status PrepareRedirect (int num_redirects_so_far)
 Prepare the request to follow a redirect link.

Static Public Attributes

static const HttpMethod DELETE
static const HttpMethod GET
 RFC 2616 DELETE.
static const HttpMethod HEAD
 RFC 2616 GET.
static const HttpMethod POST
 RFC 2616 HEAD.
static const HttpMethod PUT
 RFC 2616 POST.
static const HttpMethod PATCH
 RFC 2616 PUT.
static const StringPiece ContentType_HTML
 RFC 2068 PATCH.
static const StringPiece ContentType_JSON
 text/html
static const StringPiece ContentType_TEXT
 application/json
static const StringPiece ContentType_MULTIPART_MIXED
 text/plain
static const StringPiece ContentType_MULTIPART_RELATED
 multipart/mixed
static const StringPiece ContentType_FORM_URL_ENCODED
 multipart/related
static const StringPiece HttpHeader_AUTHORIZATION
 Any header name is valid, these are just common ones used within the api itself.
static const StringPiece HttpHeader_CONTENT_LENGTH
static const StringPiece HttpHeader_CONTENT_TYPE
 Content-Length.
static const StringPiece HttpHeader_HOST
 Content-Type.
static const StringPiece HttpHeader_LOCATION
 Host.
static const StringPiece HttpHeader_TRANSFER_ENCODING
 Location.
static const StringPiece HttpHeader_USER_AGENT
 Transfer-Encoding.

Protected Member Functions

 HttpRequest (HttpMethod method, HttpTransport *transport)
 Constructs method instance.
HttpTransporttransport () const
 Returns the transport instance bound to the request.
virtual void DoExecute (HttpResponse *response)=0
 Initiate the actually messaging for this message with the HTTP server.

Detailed Description

Denotes an HTTP request to be sent to an HTTP server.

Requests are used to send messages to HTTP servers. They are not created directly by consumer code, rather they are created by HttpTransport instances on behalf of requests from consumer code. In practice, this class will be subclassed by transport implementations as needed to store additional private state that the tranaport implementation may need. Consumer code shoudl not subclass requests, however transport implementations are required to.

This class is based on a Command Pattern for issueing HTTP requests consistent with RFC 2616, HTTP/1.1. The request instance can be given the url to invoke, along with the payload and any desired headers. The physical message exchanges with the server happen when Execute() is called.

This class is not strictly thread-safe in itself, however it is designed such that it can be safely consumed in a multi-threaded environment. The critical state that is not naturally thread-safe is managed in the thread-safe HttpRequestState class.

Although this class is abstract, it is recommended that consumer code use only this class interface so as not to depend on any specific transport implementation. Especially if the code will be compiled into libraries used by multiple applications or will run on multiple platforms.

See also:
HttpResponse
HttpTransport
HttpTransport::NewHttpRequest()

Member Typedef Documentation

typedef StringPiece HttpMethod

Methods are just a free-form StringPiece typedefed to clarify the API.

Some HTTP servers may use extensions or define non-standard methods. This type is a free-form StringPiece to accomodate those values. It is suggested, but not required, you use the standard value constants if you can.


Constructor & Destructor Documentation

virtual ~HttpRequest ( ) [virtual]

User-Agent.

Standard destructor.

The destructor is public for synchonous requests. However, asynchronous requests should instead use DestroyWhenDone() to avoid internal race conditions.

HttpRequest ( HttpMethod  method,
HttpTransport transport 
) [protected]

Constructs method instance.

Parameters:
[in]methodWhen choosing a particular HTTP method keep in mind that the server processing the URL may only support a particular supset for the given URL.
[in]transportThe transport to bind to the request. Usually requests are created by transports, so this is normally the transport that created the request. Conceptually this is the transport to use when invoking the request.

The constructor is only protected since this class is abstract.


Member Function Documentation

void AddHeader ( const StringPiece &  name,
const StringPiece &  value 
)

Adds a header, or replaces its value if it already exists.

Parameters:
[in]nameHeader names are not case sensitive.
[in]valueThe value to assign the header.

The underlying strings will be copied into this object instance.

Todo:
(ewiseblatt): 20130430 http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 says certain types of request headers can be repeated however here we are requiring request headers to be unique. We do permit repeatable response headers.
virtual void Clear ( ) [virtual]

Clears the request data, but not the options.

DataReader* content_reader ( ) const [inline]

Returns the content_reader specifying this requests's message body.

Note:
When you read from the resulting data reader, you will modify the position in the stream. If the content was already read then it may already be at the end (or in the middle) of the stream. If you are unsure, check the position and attempt to reset it if it is not at 0.
Returns:
NULL if there is no message body.
See also:
DataReader::offset()

Returns the authorization credential.

Returns:
NULL if no authorization credential has been set.
void DestroyWhenDone ( )

A safer destructor for asynchronous requests.

Destroys the request once it is done() and after notifications has been called. if the requst has already finished, the the instance will be destroyed immediately. Otherwise it will self-desruct once it is safe to do so.

virtual void DoExecute ( HttpResponse response) [protected, pure virtual]

Initiate the actually messaging for this message with the HTTP server.

Concrete classes should override this to work with the transport to actually send the request and receive the response. The method does not return until the request is done().

The caller should leave responsibility to the base class for transitioning state and running the callback. The method should set the http_code if a response is received or transport_status if the request could not be sent. It is also responsible for writing the response data into the response body_reader.

This method should not finish with both a transport_status.ok() and http_code() == 0.

See also:
HttpResponse::body_writer
Httpresponse::set_body_reader()
response()

Synchronously send the request to the designated URL and wait for the response.

This method blocks the calling thread until the response has been received and processed. The request will be done() when this call returns. If DestroyWhenDone was called (or option set) then this instance will no longer exist when the call returns. Note that since the instance owns the reponse, the response will no longer be available once this instance is destroyed.

Returns:
the response()->status().
See also:
ExecuteAsync
response()
state()
void ExecuteAsync ( HttpRequestCallback callback)

Asynchronously send the request to the designated URL then continue this thread while the server is processing the request.

param[in] callback If non-NULL the callback will be run once the request is done() for whatever reason. The caller retains ownership however typically single-use callbacks are used so the callback will self-destruct once run.

Note that the callback may or may not have been executed at the time that this call returns. If using a self-destructing instance, you should only look at the state and response in the callback.

See also:
HttpRequestState::WaitUntilDone
NewCallback()
Execute
state()
response()
const string* FindHeaderValue ( const StringPiece &  name) const

Get the value of the named header.

Returns:
NULL if the named header is not present, otherwise returns a pointer to the header value.

A non-NULL result will only be valid until a header is added or removed (or the object is destroyed).

const HttpHeaderMap& headers ( ) const [inline]

Get all the headers explicitly added to the request.

Returns:
the set of all explicitly added headers (keyed by name)
HttpMethod http_method ( ) const [inline]

Get the HTTP method for the request.

Returns:
The method bound in the constructor.

Gets a mutable options instance to configure instance-specific options.

Options should not be changed once Execute() is called or they will not take effect and can potentially confuse response processing.

Returns mutable state.

Ideally this is protected, but it is needed by MediaUploader and perhaps other situations with higher level APIs that encounter errors before it can send the request.

const HttpRequestOptions& options ( ) const [inline]

Gets request options.

util::Status PrepareRedirect ( int  num_redirects_so_far)

Prepare the request to follow a redirect link.

The target for the redirect is obtained from a response header as defined by the HTTP protocol.

Parameters:
[in]num_redirects_so_farNumber of redirects we've followed so far while trying to execute the request.
Returns:
ok if the request could be prepared and failure if not. Reasons for failure include exceeding the option limiting the number of redirects that can be followed.
Note:
This method is only intended to implement error handling on redirects. It allows the request object to change internal state to redirect itself. This should be used with caution. It is biased towards the default error handler and may not be generally applicable.

Prepares the request instance so that it can be reused again.

This method strips sensitive request headers and resets the request state. It also clears the response state. It will leave the other data including url, body, callback, and non-sensitive headers.

Returns:
ok if the request could not be prepared. The most common expected reason for failure would be that the content_body could not be reset.
void RemoveHeader ( const StringPiece &  name)

Removes the named header, if it exists.

Parameters:
[in]nameThe name of the header to remove is not case-sensitive.
HttpResponse* response ( ) const [inline]

Returns the object managing the request's response.

Although this method is on a const request, the response returned is not const. That is because reading the body affects the stream pointer, which changes its state.

void set_content_reader ( DataReader reader)

Specifies the requests message body using a DataReader.

Parameters:
[in]readerOwnership is passed to the request instance.
void set_content_type ( const StringPiece &  type) [inline]

Adds a 'Content-Type' header with the given value.

This replaces any existing 'Content-Type' header.

Parameters:
[in]typeThe new content type.
See also:
RemoveHeader()
void set_credential ( AuthorizationCredential cred) [inline]

Sets the authorization credential.

Parameters:
[in]credCan be NULL. The caller retains ownership.
void set_url ( const string &  url) [inline]

Sets the URL to invoke when the request is executed.

Parameters:
[in]urlthe desired URL.
const HttpRequestState& state ( ) const [inline]

Gets request state instance containing additional attribute values.

The request state contains the dynamic attributes requiring thread-safety. These include things like status, http response code, and where in the execution lifecycle the request currently is.

HttpTransport* transport ( ) const [inline, protected]

Returns the transport instance bound to the request.

const string& url ( ) const [inline]

Returns the URL that this request will invoke when executed.

void WillNotExecute ( util::Status  status,
HttpRequestCallback callback = NULL 
)

Indicate that the method will never Execute.

This method is intended for higher level uses where a component may own an HttpRequest but choose not to call it for some reason such as a precondition failure. This method allows the status to be pushed into the request and any asynchronous callback to be notified since the request is now considered a transport-level failrue.

Parameters:
[in]statusThe transport_status to give the request
[in]callbackIf non-NULL then run the callback after setting the status.

Member Data Documentation

const StringPiece ContentType_FORM_URL_ENCODED [static]

multipart/related

application/x-www-form-urlencoded

const StringPiece ContentType_HTML [static]

RFC 2068 PATCH.

Any content-type is valid. These are just symbolic names for ones explicitly used within the client libraries.

const StringPiece ContentType_JSON [static]

text/html

const StringPiece ContentType_MULTIPART_MIXED [static]

text/plain

const StringPiece ContentType_MULTIPART_RELATED [static]

multipart/mixed

const StringPiece ContentType_TEXT [static]

application/json

const HttpMethod DELETE [static]
const HttpMethod GET [static]

RFC 2616 DELETE.

const HttpMethod HEAD [static]

RFC 2616 GET.

const StringPiece HttpHeader_AUTHORIZATION [static]

Any header name is valid, these are just common ones used within the api itself.

const StringPiece HttpHeader_CONTENT_LENGTH [static]
const StringPiece HttpHeader_CONTENT_TYPE [static]

Content-Length.

const StringPiece HttpHeader_HOST [static]

Content-Type.

const StringPiece HttpHeader_LOCATION [static]

Host.

const StringPiece HttpHeader_TRANSFER_ENCODING [static]

Location.

const StringPiece HttpHeader_USER_AGENT [static]

Transfer-Encoding.

const HttpMethod PATCH [static]

RFC 2616 PUT.

const HttpMethod POST [static]

RFC 2616 HEAD.

const HttpMethod PUT [static]

RFC 2616 POST.


The documentation for this class was generated from the following file:
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines