Dart

Networking in Dart: An Introduction to HTTP Requests using the HttpClient Class

Gustavo Zeloni
3 min readJul 27, 2023

Networking is an essential aspect of modern applications, enabling them to interact with external services, fetch real-time data, and provide interactive user experiences. In Dart, the dart:io library offers support for making HTTP requests through the HttpClient class. In this article, we will explore how to perform HTTP requests in Dart using the HttpClient Class, and grasp the fundamental concepts of networking.

What is the HttpClient?

The HttpClient is a powerful class provided by the dart:io library that allows Dart applications to communicate over the HTTP protocol. It enables developers to send HTTP requests to remote servers, interact with RESTful APIs, and handle responses efficiently.

Setting Up the HttpClient

Before we start making HTTP requests, let’s set up the HttpClient. To do this, we’ll need to import the dart:io library and create an instance of the HttpClient class:

import 'dart:io';

void main() {
HttpClient httpClient = HttpClient();
}

Making a GET Request

Now that we have the HttpClient instance ready, let’s make a simple GET request to a remote server and fetch some data. For this example, we’ll use the https://jsonplaceholder.typicode.com API:

import 'dart:io';
import 'dart:convert';

void main() async {
HttpClient httpClient = HttpClient();
final url = Uri.parse('https://jsonplaceholder.typicode.com/posts/1');

HttpClientRequest request = await httpClient.getUrl(url);
HttpClientResponse response = await request.close();

if (response.statusCode == HttpStatus.ok) {
String responseBody = await response.transform(utf8.decoder).join();
Map<String, dynamic> data = json.decode(responseBody);
print('Received data: $data');
} else {
print('Request failed with status: ${response.statusCode}');
}
httpClient.close();
}

Making POST Requests

In addition to GET requests, HttpClient also supports other HTTP methods like POST, PUT, DELETE, etc. Let’s make a POST request with some data to the server:

import 'dart:io';
import 'dart:convert';

void main() async {
HttpClient httpClient = HttpClient();
final url = Uri.parse('https://jsonplaceholder.typicode.com/posts');

HttpClientRequest request = await httpClient.postUrl(url);
request.headers.set('Content-Type', 'application/json');
request.write(json.encode({'title': 'Sample Title', 'body': 'Sample Body'}));

HttpClientResponse response = await request.close();

if (response.statusCode == HttpStatus.created) {
String responseBody = await response.transform(utf8.decoder).join();
Map<String, dynamic> data = json.decode(responseBody);
print('Post created with ID: ${data['id']}');
} else {
print('Request failed with status: ${response.statusCode}');
}
httpClient.close();
}

Handling Errors and Cleanup

When working with networking, it’s crucial to handle errors properly and close the HttpClient when it’s no longer needed to free up system resources. We can use try-catch blocks to handle exceptions and use the httpClient.close() method to release the resources:

import 'dart:io';
import 'dart:convert';

void main() async {
HttpClient httpClient = HttpClient();
final url = Uri.parse('https://jsonplaceholder.typicode.com/posts/9999');

try {
HttpClientRequest request = await httpClient.getUrl(url);
HttpClientResponse response = await request.close();

if (response.statusCode == HttpStatus.ok) {
String responseBody = await response.transform(utf8.decoder).join();
Map<String, dynamic> data = json.decode(responseBody);
print('Received data: $data');
} else {
print('Request failed with status: ${response.statusCode}');
}
} catch (error) {
print('Error occurred: $error');
} finally {
httpClient.close();
}
}

Conclusion

In this article, we’ve introduced the HttpClient class in Dart, enabling us to perform HTTP requests, handle responses, and interact with remote servers efficiently. We explored making GET and POST requests and learned how to handle errors and clean up resources properly. Networking is a crucial aspect of modern applications, and mastering HttpClient in Dart opens up a world of possibilities to create dynamic and interactive applications.

Remember to check the official Dart documentation for HttpClient to discover more features and options that can enhance your networking capabilities further.

I hope you found this article helpful! If you have any questions or feedback, feel free to leave a comment below.

--

--