Try it yourself with our free Curl Converter tool — runs entirely in your browser, no signup needed.

How to Make HTTP requests in Dart

How to make HTTP requests in Dart

Making HTTP requests is a crucial part of many applications, allowing them to communicate with servers, APIs, and other web services. In Dart, the http package provides a convenient and efficient way to make HTTP requests. In this article, we will explore how to make HTTP requests in Dart, covering the basics, handling edge cases, common mistakes, and performance tips.

Quick Example

Here is a minimal example of making a GET request to a JSON API:

import 'package:http/http.dart' as http;

void main() async {
  final url = 'https://jsonplaceholder.typicode.com/posts';
  final response = await http.get(Uri.parse(url));

  if (response.statusCode == 200) {
    print(response.body);
  } else {
    print('Request failed with status: ${response.statusCode}');
  }
}

To run this example, add the http package to your pubspec.yaml file:

dependencies:
  http: ^0.13.3

Then, run dart pub get to install the package.

Step-by-Step Breakdown

Let's walk through the code:

  1. import 'package:http/http.dart' as http; imports the http package and assigns it the alias http.
  2. final url = 'https://jsonplaceholder.typicode.com/posts'; defines the URL of the API endpoint.
  3. final response = await http.get(Uri.parse(url)); makes a GET request to the specified URL using the http.get() function. The await keyword suspends the execution of the surrounding async function until the response is received.
  4. if (response.statusCode == 200) { ... } checks if the response status code is 200 (OK). If it is, the response body is printed to the console.
  5. print('Request failed with status: ${response.statusCode}'); prints an error message if the response status code is not 200.

Handling Edge Cases

Empty/Null Input

When making an HTTP request, it's essential to handle cases where the input URL is empty or null. Here's an example of how to do this:

void main() async {
  final url = '';
  try {
    final response = await http.get(Uri.parse(url));
    // ...
  } catch (e) {
    print('Error: $e');
  }
}

In this example, an empty string is passed to Uri.parse(), which throws a FormatException. The try-catch block catches the exception and prints an error message.

Invalid Input

Invalid input can also cause issues when making HTTP requests. For example, if the URL is malformed or contains invalid characters, the Uri.parse() function will throw a FormatException. Here's an example of how to handle this:

void main() async {
  final url = ' invalid url ';
  try {
    final response = await http.get(Uri.parse(url));
    // ...
  } catch (e) {
    print('Error: $e');
  }
}

Large Input

When dealing with large input, such as a large JSON payload, it's essential to handle cases where the input exceeds the maximum allowed size. Here's an example of how to do this:

void main() async {
  final url = 'https://jsonplaceholder.typicode.com/posts';
  final payload = 'large JSON payload';
  try {
    final response = await http.post(Uri.parse(url), body: payload);
    // ...
  } catch (e) {
    print('Error: $e');
  }
}

In this example, a large JSON payload is passed to the http.post() function. If the payload exceeds the maximum allowed size, the http package will throw a RangeError.

Unicode/Special Characters

When dealing with Unicode or special characters in URLs, it's essential to handle cases where the characters are not properly encoded. Here's an example of how to do this:

void main() async {
  final url = 'https://example.com/path with spaces';
  try {
    final response = await http.get(Uri.parse(url));
    // ...
  } catch (e) {
    print('Error: $e');
  }
}

In this example, a URL with spaces is passed to the Uri.parse() function. The Uri.parse() function will properly encode the spaces, allowing the request to succeed.

Common Mistakes

Mistake 1: Not Handling Exceptions

void main() async {
  final url = '';
  final response = await http.get(Uri.parse(url));
  // ...
}

Corrected code:

void main() async {
  final url = '';
  try {
    final response = await http.get(Uri.parse(url));
    // ...
  } catch (e) {
    print('Error: $e');
  }
}

Mistake 2: Not Checking the Response Status Code

void main() async {
  final url = 'https://jsonplaceholder.typicode.com/posts';
  final response = await http.get(Uri.parse(url));
  print(response.body);
}

Corrected code:

void main() async {
  final url = 'https://jsonplaceholder.typicode.com/posts';
  final response = await http.get(Uri.parse(url));
  if (response.statusCode == 200) {
    print(response.body);
  } else {
    print('Request failed with status: ${response.statusCode}');
  }
}

Mistake 3: Not Closing the Response Stream

void main() async {
  final url = 'https://jsonplaceholder.typicode.com/posts';
  final response = await http.get(Uri.parse(url));
  // ...
}

Corrected code:

void main() async {
  final url = 'https://jsonplaceholder.typicode.com/posts';
  final response = await http.get(Uri.parse(url));
  // ...
  response.stream.drain();
}

Performance Tips

Tip 1: Use the http Package

The http package is designed to be efficient and easy to use. It provides a simple and intuitive API for making HTTP requests.

Tip 2: Use the async and await Keywords

Using the async and await keywords allows your code to be asynchronous, which can significantly improve performance.

Tip 3: Use the stream Property

The stream property of the http package allows you to handle large responses in a streaming fashion, which can improve performance.

FAQ

Q: What is the difference between http.get() and http.post()?

A: http.get() is used for making GET requests, while http.post() is used for making POST requests.

Q: How do I handle exceptions when making HTTP requests?

A: You can handle exceptions by wrapping your code in a try-catch block.

Q: How do I check the response status code?

A: You can check the response status code by accessing the statusCode property of the response object.

Q: How do I close the response stream?

A: You can close the response stream by calling the drain() method on the stream property of the response object.

Q: What is the best way to handle large input when making HTTP requests?

A: The best way to handle large input is to use the stream property of the http package to handle the response in a streaming fashion.

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 60+ developer tools. One command: npx @codetidy/mcp