An HTTP client for communicating with an HTTP server.
Note: You should avoid directly using
HttpClientto make HTTPrequests. You can useHttpClientindirectly through theIOClientadapter inpackage:http.Using a higher-level library,like
package:http, allows you toswitch implementations with minimal changes to your code. For example,package:httpClienthas implementations for the browser and implementations that useplatform native HTTP clients on Android and iOS. UnlikeHttpClient,these native implementations work with the proxies, VPNs, etc.
Sends HTTP requests to an HTTP server and receives responses.Maintains state, including session cookies and other cookies,between multiple requests to the same server.
HttpClient contains a number of methods to send anHttpClientRequestto an Http server and receive anHttpClientResponse back.For example, you can use theget,getUrl,post, andpostUrl methodsfor GET and POST requests, respectively.
Making a simple GET request: an example
AgetUrl request is a two-step process, triggered by twoFutures.When the first future completes with anHttpClientRequest, the underlyingnetwork connection has been established, but no data has been sent.In the callback function for the first future, the HTTP headers and bodycan be set on the request. Either the first write to the request objector a call toclose sends the request to the server.
When the HTTP response is received from the server,the second future, which is returned by close,completes with anHttpClientResponse object.This object provides access to the headers and body of the response.The body is available as a stream implemented byHttpClientResponse.If a body is present, it must be read. Otherwise, it leads to resourceleaks. Consider usingHttpClientResponse.drain if the body is unused.
var client = HttpClient();try { HttpClientRequest request = await client.get('localhost', 80, '/file.txt'); // Optionally set up headers... // Optionally write to the request object... HttpClientResponse response = await request.close(); // Process the response final stringData = await response.transform(utf8.decoder).join(); print(stringData);} finally { client.close();}The future forHttpClientRequest is created by methods such asgetUrl andopen.
HTTPS connections
AnHttpClient can make HTTPS requests, connecting to a server usingthe TLS (SSL) secure networking protocol. CallinggetUrl with anhttps: scheme will work automatically, if the server's certificate issigned by a root CA (certificate authority) on the default list ofwell-known trusted CAs, compiled by Mozilla.
To add a custom trusted certificate authority, or to send a clientcertificate to servers that request one, pass aSecurityContext objectas the optionalcontext argument to theHttpClient constructor.The desired security options can be set on theSecurityContext object.
Headers
AllHttpClient requests set the following header by default:
Accept-Encoding: gzipThis allows the HTTP server to use gzip compression for the body ifpossible. If this behavior is not desired set theAccept-Encoding header to something else.To turn off gzip compression of the response, clear this header:
request.headers.removeAll(HttpHeaders.acceptEncodingHeader)Closing theHttpClient
HttpClient supports persistent connections and caches networkconnections to reuse them for multiple requests wheneverpossible. This means that network connections can be kept open forsome time after a request has completed. UseHttpClient.closeto force theHttpClient object to shut down and to close the idlenetwork connections.
Turning proxies on and off
By default theHttpClient uses the proxy configuration availablefrom the environment, seefindProxyFromEnvironment. To turn offthe use of proxies set thefindProxy property tonull.
HttpClient client = HttpClient();client.findProxy = null;Constructors
- HttpClient({SecurityContext?context})
- factory
Properties
- authenticate←Future<
bool> Function(Uriurl,Stringscheme,String?realm)? - Sets the function to be called when a site is requestingauthentication.no getter
- authenticateProxy←Future<
bool> Function(Stringhost,intport,Stringscheme,String?realm)? - Sets the function to be called when a proxy is requestingauthentication.no getter
- autoUncompress↔bool
- Gets and sets whether the body of a response will be automaticallyuncompressed.getter/setter pair
- badCertificateCallback←bool Function(X509Certificatecert,Stringhost,intport)?
- Sets a callback that will decide whether to accept a secure connectionwith a server certificate that cannot be authenticated by any of ourtrusted root certificates.no getter
- connectionFactory←Future<
ConnectionTask< Function(Uriurl,String?proxyHost,int?proxyPort)?Socket> > - Sets the function used to create socket connections.no getter
- connectionTimeout↔Duration?
- Gets and sets the connection timeout.getter/setter pair
- findProxy←String Function(Uriurl)?
- Sets the function used to resolve the proxy server to be used foropening an HTTP connection to the specified
url. If thisfunction is not set, direct connections will always be used.no getter - hashCode→int
- The hash code for this object.no setterinherited
- idleTimeout↔Duration
- Gets and sets the idle timeout of non-active persistent (keep-alive)connections.getter/setter pair
- keyLog← dynamic Function(Stringline)?
- Sets a callback that will be called when new TLS keys are exchanged withthe server. It will receive one line of text inNSS Key Log Formatfor each call. Writing these lines to a file will allow tools (such asWireshark)to decrypt communication between the this client and the server. This ismeant to allow network-level debugging of secure sockets and should notbe used in production code. For example:no getter
- maxConnectionsPerHost↔int?
- Gets and sets the maximum number of live connections, to a single host.getter/setter pair
- runtimeType→Type
- A representation of the runtime type of the object.no setterinherited
- userAgent↔String?
- Gets and sets the default value of the
User-Agentheader for all requestsgenerated by thisHttpClient.getter/setter pair
Methods
- addCredentials(
Uriurl,Stringrealm,HttpClientCredentialscredentials)→ void - Add credentials to be used for authorizing HTTP requests.
- addProxyCredentials(
Stringhost,intport,Stringrealm,HttpClientCredentialscredentials)→ void - Add credentials to be used for authorizing HTTP proxies.
- close(
{boolforce =false})→ void - Shuts down the HTTP client.
- delete(
Stringhost,intport,Stringpath)→Future< HttpClientRequest> - Opens an HTTP connection using the DELETE method.
- deleteUrl(
Uriurl)→Future< HttpClientRequest> - Opens an HTTP connection using the DELETE method.
- get(
Stringhost,intport,Stringpath)→Future< HttpClientRequest> - Opens an HTTP connection using the GET method.
- getUrl(
Uriurl)→Future< HttpClientRequest> - Opens an HTTP connection using the GET method.
- head(
Stringhost,intport,Stringpath)→Future< HttpClientRequest> - Opens an HTTP connection using the HEAD method.
- headUrl(
Uriurl)→Future< HttpClientRequest> - Opens an HTTP connection using the HEAD method.
- noSuchMethod(
Invocationinvocation)→ dynamic - Invoked when a nonexistent method or property is accessed.inherited
- open(
Stringmethod,Stringhost,intport,Stringpath)→Future< HttpClientRequest> - Opens an HTTP connection.
- openUrl(
Stringmethod,Uriurl)→Future< HttpClientRequest> - Opens an HTTP connection.
- patch(
Stringhost,intport,Stringpath)→Future< HttpClientRequest> - Opens an HTTP connection using the PATCH method.
- patchUrl(
Uriurl)→Future< HttpClientRequest> - Opens an HTTP connection using the PATCH method.
- post(
Stringhost,intport,Stringpath)→Future< HttpClientRequest> - Opens an HTTP connection using the POST method.
- postUrl(
Uriurl)→Future< HttpClientRequest> - Opens an HTTP connection using the POST method.
- put(
Stringhost,intport,Stringpath)→Future< HttpClientRequest> - Opens an HTTP connection using the PUT method.
- putUrl(
Uriurl)→Future< HttpClientRequest> - Opens an HTTP connection using the PUT method.
- toString(
)→String - A string representation of this object.inherited
Operators
- operator ==(
Objectother)→bool - The equality operator.inherited
Static Properties
- enableTimelineLogging↔bool
- Current state of HTTP request logging from allHttpClients to thedeveloper timeline.getter/setter pair
Static Methods
Constants
- defaultHttpPort→ constint
- defaultHttpsPort→ constint