20042010 Ericsson AB. All Rights Reserved. The contents of this file are subject to the Erlang Public License, Version 1.1, (the "License"); you may not use this file except in compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at http://www.erlang.org/. Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. httpc Ingela Anderton Andin
httpc An HTTP/1.1 client

This module provides the API to a HTTP/1.1 compatible client according to RFC 2616, caching is currently not supported.

When starting the Inets application a manager process for the default profile will be started. The functions in this API that does not explicitly use a profile will accesses the default profile. A profile keeps track of proxy options, cookies and other options that can be applied to more than one request.

If the scheme https is used the ssl application needs to be started.

Also note that pipelining will only be used if the pipeline timeout is set, otherwise persistent connections without pipelining will be used e.i. the client always waits for the previous response before sending the next request.

There are some usage examples in the Inets User's Guide.

COMMON DATA TYPES

Type definitions that are used more than once in this module:

HTTP DATA TYPES

Type definitions that are related to HTTP:

For more information about HTTP see rfc 2616

SSL DATA TYPES

Some type definitions relevant when using https, for details ssl(3):

HTTP CLIENT SERVICE START/STOP

A HTTP client can be configured to start when starting the inets application or started dynamically in runtime by calling the inets application API inets:start(httpc, ServiceConfig), or inets:start(httpc, ServiceConfig, How) see inets(3) Below follows a description of the available configuration options.

{profile, profile()} Name of the profile, see common data types below, this option is mandatory. {data_dir, path()} Directory where the profile may save persistent data, if omitted all cookies will be treated as session cookies.

The client can be stopped using inets:stop(httpc, Pid) or inets:stop(httpc, Profile).

request(Url) -> request(Url, Profile) -> {ok, Result} | {error, Reason} Sends a get HTTP-request Url = url() Result = {status_line(), headers(), body()} | {status_code(), body()} | request_id() Profile = profile() Reason = term()

Equivalent to httpc:request(get, {Url, []}, [], []).

request(Method, Request, HTTPOptions, Options) -> request(Method, Request, HTTPOptions, Options, Profile) -> {ok, Result} | {ok, saved_to_file} | {error, Reason} Sends a HTTP-request Method = method() Request = request() HTTPOptions = http_options() http_options() = [http_option()] http_option() = {timeout, timeout()} | {connect_timeout, timeout()} | {ssl, ssl_options()} | {ossl, ssl_options()} | {essl, ssl_options()} | {autoredirect, boolean()} | {proxy_auth, {userstring(), passwordstring()}} | {version, http_version()} | {relaxed, boolean()} timeout() = integer() >= 0 | infinity Options = options() options() = [option()] option() = {sync, boolean()} | {stream, stream_to()} | {body_format, body_format()} | {full_result, boolean()} | {headers_as_is, boolean() | {socket_opts, socket_opts()} | {receiver, receiver()}} stream_to() = none | self | {self, once} | filename() socket_opts() = [socket_opt()] receiver() = pid() | function()/1 | {Module, Function, Args} Module = atom() Function = atom() Args = list() body_format() = string | binary Result = {status_line(), headers(), body()} | {status_code(), body()} | request_id() Profile = profile() Reason = {connect_failed, term()} | {send_failed, term()} | term()

Sends a HTTP-request. The function can be both synchronous and asynchronous. In the later case the function will return {ok, RequestId} and later on the information will be delivered to the receiver depending on that value.

Http option (http_option()) details:

Timeout time for the request.

The clock start ticking as soon as the request has been sent.

Time is in milliseconds.

Defaults to infinity.

Connection timeout time, used during the initial request, when the client is connecting to the server.

Time is in milliseconds.

Defaults to the value of the timeout option.

This is the default ssl config option, currently defaults to ossl, see below.

Defaults to [].

If using the OpenSSL based (old) implementation of SSL, these SSL-specific options are used.

Defaults to [].

If using the Erlang based (new) implementation of SSL, these SSL-specific options are used.

Defaults to [].

Should the client automatically retreive the information from the new URI and return that as the result instead of a 30X-result code.

Note that for some 30X-result codes automatic redirect is not allowed in these cases the 30X-result will always be returned.

Defaults to true.

A proxy-authorization header using the provided user name and password will be added to the request.

Can be used to make the client act as an HTTP/1.0 or HTTP/0.9 client. By default this is an HTTP/1.1 client. When using HTTP/1.0 persistent connections will not be used.

Defaults to the trsing "HTTP/1.1".

If set to true workarounds for known server deviations from the HTTP-standard are enabled.

Defaults to false.

Option (option()) details:

Shall the request be synchronous or asynchronous.

Defaults to true.

Streams the body of a 200 or 206 response to the calling process or to a file. When streaming to the calling process using the option self the the following stream messages will be sent to that process: {http, {RequestId, stream_start, Headers}, {http, {RequestId, stream, BinBodyPart}, {http, {RequestId, stream_end, Headers}. When streaming to to the calling processes using the option {self, once} the first message will have an additional element e.i. {http, {RequestId, stream_start, Headers, Pid}, this is the process id that should be used as an argument to http:stream_next/1 to trigger the next message to be sent to the calling process.

Note that it is possible that chunked encoding will add headers so that there are more headers in the stream_end message than in the stream_start. When streaming to a file and the request is asynchronous the message {http, {RequestId, saved_to_file}} will be sent.

Defaults to none.

Defines if the body shall be delivered as a string or as a binary. This option is only valid for the synchronous request.

Defaults to string.

Should a "full result" be returned to the caller (that is, the body, the headers and the entire status-line) or not (the body and the status code).

Defaults to true.

Shall the headers provided by the user be made lower case or be regarded as case sensitive.

Note that the http standard requires them to be case insenstive. This feature should only be used if there is no other way to communicate with the server or for testing purpose. Also note that when this option is used no headers will be automatically added, all necessary headers has to be provided by the user.

Defaults to false.

Socket options to be used for this and subsequent request(s).

Overrides any value set by the set_options function.

Note that the validity of the options are not checked in any way.

Note that this may change the socket behaviour (see inet:setopts/2) for an already existing, and therefor already connected request handler.

By defaults the socket options set by the set_options/1,2 function is used when establishing connection.

Defines how the client will deliver the result for a asynchroneous request (sync has the value false).

Message(s) will be sent to this process in the format:

{http, ReplyInfo}

Information will be delivered to the receiver via calls to the provided fun:

Receiver(ReplyInfo)

Information will be delivered to the receiver via calls to the callback function:

apply(Module, Function, [ReplyInfo | Args])

In all cases above, ReplyInfo has the following structure:

{RequestId, saved_to_file}
{RequestId, {error, Reason}}
{RequestId, Result}
{RequestId, stream_start, Headers}
{RequestId, stream_start, Headers, HandlerPid}
{RequestId, stream,       BinBodyPart}
{RequestId, stream_end,   Headers}

Defaults to the pid() of the process calling the request function (self()).

cancel_request(RequestId) -> cancel_request(RequestId, Profile) -> ok Cancels an asynchronous HTTP-request. RequestId = request_id() - A unique identifier as returned by request/4 Profile = profile()

Cancels an asynchronous HTTP-request.

set_options(Options) -> set_options(Options, Profile) -> ok | {error, Reason} Sets options to be used for subsequent requests. Options = [Option] Option = {proxy, {Proxy, NoProxy}} | {max_sessions, MaxSessions} | {max_keep_alive_length, MaxKeepAlive} | {keep_alive_timeout, KeepAliveTimeout} | {max_pipeline_length, MaxPipeline} | {pipeline_timeout, PipelineTimeout} | {cookies, CookieMode} | {ipfamily, IpFamily} | {ip, IpAddress} | {port, Port} | {socket_opts, socket_opts()} | {verbose, VerboseMode} Proxy = {Hostname, Port} Hostname = string() ex: "localhost" or "foo.bar.se" Port = integer() ex: 8080 socket_opts() = [socket_opt()] The options are appended to the socket options used by the client. These are the default values when a new request handler is started (for the initial connect). They are passed directly to the underlying transport (gen_tcp or ssl) without verification! NoProxy = [NoProxyDesc] NoProxyDesc = DomainDesc | HostName | IPDesc DomainDesc = "*.Domain" ex: "*.ericsson.se" IpDesc = string() ex: "134.138" or "[FEDC:BA98" (all IP-addresses starting with 134.138 or FEDC:BA98), "66.35.250.150" or "[2010:836B:4179::836B:4179]" (a complete IP-address). MaxSessions = integer() Default is 2. Maximum number of persistent connections to a host. MaxKeepAlive = integer() Default is 5. Maximum number of outstanding requests on the same connection to a host. KeepAliveTimeout = integer() Default is 120000 (= 2 min). If a persistent connection is idle longer than the keep_alive_timeout the client will close the connection. The server may also have a such a time out but you should not count on it! MaxPipeline = integer() Default is 2. Maximum number of outstanding requests on a pipelined connection to a host. PipelineTimeout = integer() Default is 0, which will result in pipelining not being used. If a persistent connection is idle longer than the pipeline_timeout the client will close the connection. CookieMode = enabled | disabled | verify Default is disabled. If Cookies are enabled all valid cookies will automatically be saved in the client manager's cookie database. If the option verify is used the function http:verify_cookie/2 has to be called for the cookie to be saved. IpFamily = inet | inet6 | inet6fb4 By default inet. When it is set to inet6fb4 you can use both ipv4 and ipv6. It first tries inet6 and if that does not works falls back to inet. The option is here to provide a workaround for buggy ipv6 stacks to ensure that ipv4 will always work. IpAddress = ip_address() If the host has several network interfaces, this option specifies which one to use. See gen_tcp:connect/3,4 for more info. Port = integer() Specify which local port number to use. See gen_tcp:connect/3,4 for more info. VerboseMode = false | verbose | debug | trace Default is false. This option is used to switch on (or off) different levels of erlang trace on the client. It is a debug feature. Profile = profile()

Sets options to be used for subsequent requests.

If possible the client will keep its connections alive and use persistent connections with or without pipeline depending on configuration and current circumstances. The HTTP/1.1 specification does not provide a guideline for how many requests that would be ideal to be sent on a persistent connection, this very much depends on the application. Note that a very long queue of requests may cause a user perceived delays as earlier request may take a long time to complete. The HTTP/1.1 specification does suggest a limit of 2 persistent connections per server, which is the default value of the max_sessions option.

stream_next(Pid) -> ok Triggers the next message to be streamed, e.i. same behavior as active once for sockets. Pid = pid() - as received in the stream_start message

Triggers the next message to be streamed, e.i. same behavior as active once for sockets.

store_cookie(SetCookieHeaders, Url) -> store_cookie(SetCookieHeaders, Url, Profile) -> ok | {error, Reason} Saves the cookies defined in SetCookieHeaders in the client profile's cookie database. SetCookieHeaders = headers() - where field = "set-cookie" Url = url() Profile = profile()

Saves the cookies defined in SetCookieHeaders in the client profile's cookie database. You need to call this function if you set the option cookies to verify. If no profile is specified the default profile will be used.

cookie_header(Url) -> cookie_header(Url, Profile) -> header() | {error, Rason} Returns the cookie header that would be sent when making a request to Url using the profile Profile. Url = url() Profile = profile()

Returns the cookie header that would be sent when making a request to Url using the profile Profile. If no profile is specified the default profile will be used.

reset_cookies() -> void() reset_cookies(Profile) -> void() Reset the cookie database. Profile = profile()

Resets (clears) the cookie database for the specified Profile. If no profile is specified the default profile will be used.

which_cookies() -> cookies() which_cookies(Profile) -> cookies() Dumps out the entire cookie database. Profile = profile() cookies() = [cooie_stores()] cookie_stores() = {cookies, icookies()} | {session_cookies, icookies()} icookies() = [icookie()] cookie() = term()

This function produces a list of the entire cookie database. It is intended for debugging/testing purposes. If no profile is specified the default profile will be used.

SEE ALSO

RFC 2616, inets(3), gen_tcp(3), ssl(3)