This tutorial shows you how to create HTTP request in Dart using various methods (GET, POST, PUT, PATCH, DELETE), including how to add headers, process HTTP response, and set timeout. This also applies for any Dart frameworks including Flutter.
Dependencies
Dart has HttpClient
class which allows us to make HTTP requests. But it's not very easy to use that library. Fortunately, Dart also provides a high-level package called http
. In this tutorial, I'll only show you how to use http
.
Examples
First, we need to import Dart's http library. In this example, we'll import it as Http
.
import 'package:http/http.dart' as Http;
GET Request
To send a GET request, use Http.get
. You are only required to pass the request URL. Optionally, you can also send request headers which is of type Map<String, String>
.
import 'dart:collection';
import 'package:http/http.dart' as Http;
main() async {
String url = 'http://example.com/api/items/1';
Map<String, String> headers = new HashMap();
headers.putIfAbsent('Accept', () => 'application/json');
Http.Response response = await Http.get(
url,
headers: headers,
);
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
}
POST Request
In addition to URL (required) and optional headers
, it also supports body
and encoding
. If you want to send JSON object as the body, you have to encode it first using dart:collection
's jsonEncode
.
import 'dart:collection';
import 'package:http/http.dart' as Http;
main() async {
String url = 'http://example.com/api/items';
Map<String, String> headers = new HashMap();
headers['Accept'] = 'application/json';
headers['Content-type'] = 'application/json';
Http.Response response = await Http.post(
url,
headers: headers,
body: jsonEncode({'name': 'Item One', 'quantity': 1}),
encoding: Encoding.getByName('utf-8')
);
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
}
The response body is a string. If it represents a JSON object, you'll need to deserialize the string into an object.
PATCH Request
Use http.patch
, parameters are the same as POST
.
PUT Request
Use http.put
, parameters are the same as POST
.
DELETE Request
Use http.delete
, parameters are the same as GET
.
Timeout Handling
Setting timeout is a common thing if you call an API as we cannot guarantee we'll get the response within a certain time. It's also a good practice as it doesn't make the application waits too long to receive a response.
There is no option to set timeout using Dart's http
. However, as it returns Future
, we can set timeout on the Future
.
Http.Response response = await Http.get(
url,
headers: headers,
);
.timeout(const Duration(seconds: 10));
The example above sets timeout to 10 second. If it has been 10 seconds and no response received, it will throw TimeoutException
Error Handling
By default, if the server that processes the request returns error, it will not throw error. You can determine whether it's failed or not by processing the response which is done by reading the value of statusCode
and body
. However, errors can still happen. For example, if the URL is invalid or if you set timeout like the above example. To be able to catch TimeoutException
, you need to add import 'dart:async';
first, then use try
..catch
block to wrap the code.
try {
Http.Response response = await Http.get(
url,
headers: headers,
)
.timeout(const Duration(seconds: 1));
} on TimeoutException catch (e) {
print('Timeout');
} on Error catch (e) {
print('Error: $e');
}