Dart API Referencedart:ioHttpClient

HttpClient abstract class

The HttpClient class implements the client side of the HTTP protocol. It contains a number of methods to send a HTTP request to a HTTP server and receive a HTTP response back.

This is a two-step process, triggered by two futures. When the first future completes with a HttpClientRequest the underlying network connection has been established, but no data has yet been sent. The HTTP headers and body can be set on the request, and close is called to sent it to the server.

The second future, which is returned by close, completes with an HttpClientResponse object when the response is received from the server. This object contains the headers and body of the response.

The future for HttpClientRequest is created by methods such as getUrl and open.

When the HTTP response is ready a HttpClientResponse object is provided which provides access to the headers and body of the response.

HttpClient client = new HttpClient();
client.getUrl(Uri.parse("http://www.example.com/"))
    .then((HttpClientRequest request) {
      // Prepare the request then call close on it to send it.
      return request.close();
    })
    .then((HttpClientResponse response) {
     // Process the response.
    });

All HttpClient requests set the following header by default:

Accept-Encoding: gzip

This allows the HTTP server to use gzip compression for the body if possible. If this behavior is not desired set the "Accept-Encoding" header to something else.

The HttpClient supports persistent connections and caches network connections to reuse then for multiple requests whenever possible. This means that network connections can be kept open for some time after a request have completed. Use HttpClient.close to force shut down the HttpClient object and close the idle network connections.

By default the HttpClient uses the proxy configuration available from the environment, see findProxyFromEnvironment. To turn off the use of proxies all together set the findProxy property to null.

HttpClient client = new HttpClient();
client.findProxy = null;
abstract class HttpClient {
 static const int DEFAULT_HTTP_PORT = 80;
 static const int DEFAULT_HTTPS_PORT = 443;

 factory HttpClient() => new _HttpClient();

 /**
  * Opens a HTTP connection. The returned [HttpClientRequest] is used to
  * fill in the content of the request before sending it. The 'host' header for
  * the request will be set to the value [host]:[port]. This can be overridden
  * through the [HttpClientRequest] interface before the request is sent.
  * NOTE if [host] is an IP address this will still be set in the 'host'
  * header.
  */
 Future<HttpClientRequest> open(String method,
                                String host,
                                int port,
                                String path);

 /**
  * Opens a HTTP connection. The returned [HttpClientRequest] is used to
  * fill in the content of the request before sending it. The 'hosth header for
  * the request will be set to the value [host]:[port]. This can be overridden
  * through the [HttpClientRequest] interface before the request is sent.
  * NOTE if [host] is an IP address this will still be set in the 'host'
  * header.
  */
 Future<HttpClientRequest> openUrl(String method, Uri url);

 /**
  * Opens a HTTP connection using the GET method. See [open] for
  * details. Using this method to open a HTTP connection will set the
  * content length to 0.
  */
 Future<HttpClientRequest> get(String host, int port, String path);

 /**
  * Opens a HTTP connection using the GET method. See [openUrl] for
  * details. Using this method to open a HTTP connection will set the
  * content length to 0.
  */
 Future<HttpClientRequest> getUrl(Uri url);

 /**
  * Opens a HTTP connection using the POST method. See [open] for details.
  */
 Future<HttpClientRequest> post(String host, int port, String path);

 /**
  * Opens a HTTP connection using the POST method. See [openUrl] for details.
  */
 Future<HttpClientRequest> postUrl(Uri url);

 /**
  * Sets the function to be called when a site is requesting
  * authentication. The URL requested and the security realm from the
  * server are passed in the arguments [url] and [realm].
  *
  * The function returns a [Future] which should complete when the
  * authentication has been resolved. If credentials cannot be
  * provided the [Future] should complete with [false]. If
  * credentials are available the function should add these using
  * [addCredentials] before completing the [Future] with the value
  * [true].
  *
  * If the [Future] completes with true the request will be retried
  * using the updated credentials. Otherwise response processing will
  * continue normally.
  */
 set authenticate(Future<bool> f(Uri url, String scheme, String realm));

 /**
  * Add credentials to be used for authorizing HTTP requests.
  */
 void addCredentials(Uri url, String realm, HttpClientCredentials credentials);

 /**
  * Sets the function used to resolve the proxy server to be used for
  * opening a HTTP connection to the specified [url]. If this
  * function is not set, direct connections will always be used.
  *
  * The string returned by [f] must be in the format used by browser
  * PAC (proxy auto-config) scripts. That is either
  *
  *   "DIRECT"
  *
  * for using a direct connection or
  *
  *   "PROXY host:port"
  *
  * for using the proxy server [:host:] on port [:port:].
  *
  * A configuration can contain several configuration elements
  * separated by semicolons, e.g.
  *
  *   "PROXY host:port; PROXY host2:port2; DIRECT"
  *
  * The static function [findProxyFromEnvironment] on this class can
  * be used to implement proxy server resolving based on environment
  * variables.
  */
 set findProxy(String f(Uri url));

 /**
  * Function for resolving the proxy server to be used for a HTTP
  * connection from the proxy configuration specified through
  * environment variables.
  *
  * The following environment variables are taken into account:
  *
  *     http_proxy
  *     https_proxy
  *     no_proxy
  *     HTTP_PROXY
  *     HTTPS_PROXY
  *     NO_PROXY
  *
  * [:http_proxy:] and [:HTTP_PROXY:] specify the proxy server to use for
  * http:// urls. Use the format [:hostname:port:]. If no port is used a
  * default of 1080 will be used. If both are set the lower case one takes
  * precedence.
  *
  * [:https_proxy:] and [:HTTPS_PROXY:] specify the proxy server to use for
  * https:// urls. Use the format [:hostname:port:]. If no port is used a
  * default of 1080 will be used. If both are set the lower case one takes
  * precedence.
  *
  * [:no_proxy:] and [:NO_PROXY:] specify a comma separated list of
  * postfixes of hostnames for which not to use the proxy
  * server. E.g. the value "localhost,127.0.0.1" will make requests
  * to both "localhost" and "127.0.0.1" not use a proxy. If both are set
  * the lower case one takes precedence.
  *
  * To activate this way of resolving proxies assign this function to
  * the [findProxy] property on the [HttpClient].
  *
  *     HttpClient client = new HttpClient();
  *     client.findProxy = HttpClient.findProxyFromEnvironment;
  *
  * If you don't want to use the system environment you can use a
  * different one by wrapping the function.
  *
  *     HttpClient client = new HttpClient();
  *     client.findProxy = (url) {
  *       return HttpClient.findProxyFromEnvironment(
  *           url, {"http_proxy": ..., "no_proxy": ...});
  *     }
  *
  * If a proxy requires authentication it is possible to configure
  * the username and password as well. Use the format
  * [:username:password@hostname:port:] to include the username and
  * password. Alternatively the API [addProxyCredentials] can be used
  * to set credentials for proxies which require authentication.
  */
 static String findProxyFromEnvironment(Uri url,
                                        {Map<String, String> environment}) {
   return _HttpClient._findProxyFromEnvironment(url, environment);
 }

 /**
  * Sets the function to be called when a proxy is requesting
  * authentication. Information on the proxy in use and the security
  * realm for the authentication are passed in the arguments [host],
  * [port] and [realm].
  *
  * The function returns a [Future] which should complete when the
  * authentication has been resolved. If credentials cannot be
  * provided the [Future] should complete with [false]. If
  * credentials are available the function should add these using
  * [addProxyCredentials] before completing the [Future] with the value
  * [true].
  *
  * If the [Future] completes with [true] the request will be retried
  * using the updated credentials. Otherwise response processing will
  * continue normally.
  */
 set authenticateProxy(
     Future<bool> f(String host, int port, String scheme, String realm));

 /**
  * Add credentials to be used for authorizing HTTP proxies.
  */
 void addProxyCredentials(String host,
                          int port,
                          String realm,
                          HttpClientCredentials credentials);

 /**
  * Shutdown the HTTP client. If [force] is [:false:] (the default)
  * the [:HttpClient:] will be kept alive until all active
  * connections are done. If [force] is [:true:] any active
  * connections will be closed to immediately release all
  * resources. These closed connections will receive an [:onError:]
  * callback to indicate that the client was shutdown. In both cases
  * trying to establish a new connection after calling [shutdown]
  * will throw an exception.
  */
 void close({bool force: false});
}

Static Properties

const int DEFAULT_HTTP_PORT #

static const int DEFAULT_HTTP_PORT = 80

const int DEFAULT_HTTPS_PORT #

static const int DEFAULT_HTTPS_PORT = 443

Static Methods

String findProxyFromEnvironment(Uri url, {Map<String, String> environment}) #

Function for resolving the proxy server to be used for a HTTP connection from the proxy configuration specified through environment variables.

The following environment variables are taken into account:

http_proxy
https_proxy
no_proxy
HTTP_PROXY
HTTPS_PROXY
NO_PROXY

http_proxy and HTTP_PROXY specify the proxy server to use for http:// urls. Use the format hostname:port. If no port is used a default of 1080 will be used. If both are set the lower case one takes precedence.

https_proxy and HTTPS_PROXY specify the proxy server to use for https:// urls. Use the format hostname:port. If no port is used a default of 1080 will be used. If both are set the lower case one takes precedence.

no_proxy and NO_PROXY specify a comma separated list of postfixes of hostnames for which not to use the proxy server. E.g. the value "localhost,127.0.0.1" will make requests to both "localhost" and "127.0.0.1" not use a proxy. If both are set the lower case one takes precedence.

To activate this way of resolving proxies assign this function to the findProxy property on the HttpClient.

HttpClient client = new HttpClient();
client.findProxy = HttpClient.findProxyFromEnvironment;

If you don't want to use the system environment you can use a different one by wrapping the function.

HttpClient client = new HttpClient();
client.findProxy = (url) {
  return HttpClient.findProxyFromEnvironment(
      url, {"http_proxy": ..., "no_proxy": ...});
}

If a proxy requires authentication it is possible to configure the username and password as well. Use the format username:password@hostname:port to include the username and password. Alternatively the API addProxyCredentials can be used to set credentials for proxies which require authentication.

static String findProxyFromEnvironment(Uri url,
                                      {Map<String, String> environment}) {
 return _HttpClient._findProxyFromEnvironment(url, environment);
}

Constructors

factory HttpClient() #

factory HttpClient() => new _HttpClient();

Properties

abstract dynamic set authenticate(Future<bool> f(Uri url, String scheme, String realm)) #

Sets the function to be called when a site is requesting authentication. The URL requested and the security realm from the server are passed in the arguments url and realm.

The function returns a Future which should complete when the authentication has been resolved. If credentials cannot be provided the Future should complete with false. If credentials are available the function should add these using addCredentials before completing the Future with the value true.

If the Future completes with true the request will be retried using the updated credentials. Otherwise response processing will continue normally.

abstract dynamic set authenticateProxy(Future<bool> f(String host, int port, String scheme, String realm)) #

Sets the function to be called when a proxy is requesting authentication. Information on the proxy in use and the security realm for the authentication are passed in the arguments host, port and realm.

The function returns a Future which should complete when the authentication has been resolved. If credentials cannot be provided the Future should complete with false. If credentials are available the function should add these using addProxyCredentials before completing the Future with the value true.

If the Future completes with true the request will be retried using the updated credentials. Otherwise response processing will continue normally.

abstract dynamic set findProxy(String f(Uri url)) #

Sets the function used to resolve the proxy server to be used for opening a HTTP connection to the specified url. If this function is not set, direct connections will always be used.

The string returned by f must be in the format used by browser PAC (proxy auto-config) scripts. That is either

"DIRECT"

for using a direct connection or

"PROXY host:port"

for using the proxy server host on port port.

A configuration can contain several configuration elements separated by semicolons, e.g.

"PROXY host:port; PROXY host2:port2; DIRECT"

The static function findProxyFromEnvironment on this class can be used to implement proxy server resolving based on environment variables.

Methods

abstract void addCredentials(Uri url, String realm, HttpClientCredentials credentials) #

Add credentials to be used for authorizing HTTP requests.

abstract void addProxyCredentials(String host, int port, String realm, HttpClientCredentials credentials) #

Add credentials to be used for authorizing HTTP proxies.

abstract void close({bool force: false}) #

Shutdown the HTTP client. If force is false (the default) the HttpClient will be kept alive until all active connections are done. If force is true any active connections will be closed to immediately release all resources. These closed connections will receive an onError callback to indicate that the client was shutdown. In both cases trying to establish a new connection after calling shutdown will throw an exception.

abstract Future<HttpClientRequest> get(String host, int port, String path) #

Opens a HTTP connection using the GET method. See open for details. Using this method to open a HTTP connection will set the content length to 0.

abstract Future<HttpClientRequest> getUrl(Uri url) #

Opens a HTTP connection using the GET method. See openUrl for details. Using this method to open a HTTP connection will set the content length to 0.

abstract Future<HttpClientRequest> open(String method, String host, int port, String path) #

Opens a HTTP connection. The returned HttpClientRequest is used to fill in the content of the request before sending it. The 'host' header for the request will be set to the value host: port. This can be overridden through the HttpClientRequest interface before the request is sent. NOTE if host is an IP address this will still be set in the 'host' header.

abstract Future<HttpClientRequest> openUrl(String method, Uri url) #

Opens a HTTP connection. The returned HttpClientRequest is used to fill in the content of the request before sending it. The 'hosth header for the request will be set to the value host:port. This can be overridden through the HttpClientRequest interface before the request is sent. NOTE if host is an IP address this will still be set in the 'host' header.

abstract Future<HttpClientRequest> post(String host, int port, String path) #

Opens a HTTP connection using the POST method. See open for details.

abstract Future<HttpClientRequest> postUrl(Uri url) #

Opens a HTTP connection using the POST method. See openUrl for details.