Dart HttpClient
last modified January 28, 2024
In this article we show how to create HTTP requests in Dart with HttpClient. Practical examples demonstrate the usage of the library.
Dart HttpClient
The HttpClient
is an HTTP client for communicating with an HTTP
server. It sends HTTP requests to an HTTP server and receives responses.
It is located in the dart:io
library.
Dart HttpClient GET request
With the GET method, we request a representation of the given resource.
import 'dart:convert'; import 'dart:io'; void main() async { final client = HttpClient(); final host = 'webcode.me'; final port = 80; final path = '/'; try { final req = await client.get(host, port, path); final resp = await req.close(); final data = await resp.transform(utf8.decoder).join(); print(data); } finally { client.close(); } }
In the program, we retrieve a home page of a simple website.
import 'dart:io';
We import the dart:io
library where HttpClient
is
located.
final client = HttpClient();
We create an instance of the HttpClient
.
final host = 'webcode.me'; final port = 80; final path = '/';
These are parts of the web resource.
final req = await client.get(host, port, path);
The get
member function opens an HTTP connection using the HTTP GET
method.
final resp = await req.close();
With close
, we finish the request and retrieve the HTTP response.
final data = await resp.transform(utf8.decoder).join();
We process the response into the UTF8 data.
} finally { client.close(); }
Finally, we call close
. It forces the HttpClient
object to shut down and to close the idle network connections.
$ dart main.dart <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="format.css"> <title>My html page</title> </head> <body> <p> Today is a beautiful day. We go swimming and fishing. </p> <p> Hello there. How are you? </p> </body> </html>
Alternatively, we can use the getUrl
member function.
import 'dart:convert'; import 'dart:io'; void main() async { var client = HttpClient(); try { var request = await client.getUrl(Uri.parse('http://webcode.me')); var response = await request.close(); var data = await response.transform(utf8.decoder).join(); print(data); } finally { client.close(); } }
The program generates a GET request to the web resource with
getUrl
. The url is parsed with Uri.parse
.
Dart HttpClient HEAD request
The HTTP HEAD method returns the headers without the body.
import 'dart:io'; void main() async { var client = HttpClient(); try { var req = await client.headUrl(Uri.parse('http://webcode.me')); var resp = await req.close(); print(resp.headers); } finally { client.close(); } }
We generate a HEAD request with headUrl
.
$ dart main.dart connection: keep-alive content-type: text/html last-modified: Sun, 23 Jan 2022 10:39:25 GMT date: Wed, 01 Mar 2023 19:56:09 GMT content-encoding: gzip server: nginx/1.6.2
Dart HttpClient user agent
The User-Agent request header is a string that lets servers and network peers identify the application, operating system, vendor, and/or version of the requesting user agent.
import 'dart:convert'; import 'dart:io'; void main() async { final client = HttpClient(); client.userAgent = 'dart program'; try { final req = await client.getUrl(Uri.parse('http://webcode.me/ua.php')); final resp = await req.close(); final data = await resp.transform(utf8.decoder).join(); print(data); } finally { client.close(); } }
The example sets a User-Agent header for its GET request. The requested resource simply returns the client's User-Agent string.
client.userAgent = 'dart program';
We set the user agent via the userAgent
property.
$ dart main.dart dart program
Alternatively, we can set the header ourselves.
import 'dart:convert'; import 'dart:io'; void main() async { final client = HttpClient(); try { final req = await client.getUrl(Uri.parse('http://webcode.me/ua.php')) ..headers.set("User-Agent", "Dart program"); final resp = await req.close(); final data = await resp.transform(utf8.decoder).join(); print(data); } finally { client.close(); } }
In this program we set the User-Agent
header explicitly through
the headers
property.
Dart HttpClient query strings
Query string is a part of the URL which is used to add some data to the request for the resource. It is often a sequence of key/value pairs. It follows the path and starts with the ? character.
import 'dart:convert'; import 'dart:io'; void main() async { final client = HttpClient(); try { final qpars = { 'name': 'John Doe', 'occupation': 'gardener', }; final url = Uri.http("webcode.me", "qs.php", qpars); final request = await client.getUrl(url); final response = await request.close(); final data = await response.transform(utf8.decoder).join(); print(data); } finally { client.close(); } }
We pass the query parameters to a resource which returns them in a JSON format.
final qpars = { 'name': 'John Doe', 'occupation': 'gardener', };
We have two key/value pairs.
final url = Uri.http("webcode.me", "qs.php", qpars);
The query parameters are passed as the third parameter of the
Uri.http
.
$ dart main.dart {"name":"John Doe","occupation":"gardener"}
Dart HttpClient POST JSON
The HTTP POST method sends data to the server. The type of the body of the
request is indicated by the Content-Type
header.
import 'dart:convert'; import 'dart:io'; void main() async { final client = HttpClient(); try { final req = await client.postUrl(Uri.parse("https://httpbin.org/post")); req.headers .set(HttpHeaders.contentTypeHeader, "application/json; charset=UTF-8"); req.write('{"name": "John Doe","occupation": "gardener"}'); final resp = await req.close(); final data = await resp.transform(utf8.decoder).join(); print(data); } finally { client.close(); } }
In the example, we post JSON data.
final req = await client.postUrl(Uri.parse("https://httpbin.org/post"));
We post data with postUrl
member function.
req.headers .set(HttpHeaders.contentTypeHeader, "application/json; charset=UTF-8");
We set the content type to application/json
.
req.write('{"name": "John Doe","occupation": "gardener"}');
We write the JSON to the request object.
final data = await resp.transform(utf8.decoder).join(); print(data);
We process the response and print the decoded data.
$ dart main.dart { "args": {}, "data": "{\"name\": \"John Doe\",\"occupation\": \"gardener\"}", "files": {}, }, ... "url": "https://httpbin.org/post" }
Source
Dart HttpClient - documentation
In this article we have created HTTP requests in Dart using the built-in
HttpClient
class.
Author
List all Dart tutorials.