乐闻世界logo
搜索文章和话题

How do you add query parameters to a Dart http request?

1个答案

1

When working with HTTP requests in Dart, you can use the http package to send network requests. When adding query parameters to requests, you can either manually construct the URL or use the Uri class to generate a URL with query parameters more conveniently. The following outlines the steps and examples for adding query parameters to a GET request using the Uri class:

Step 1: Add the http package dependency

First, ensure that your Dart project includes the http package dependency. You can add the following dependency to your pubspec.yaml file:

yaml
dependencies: http: ^0.13.3

Then run pub get to install the dependency.

Step 2: Import the http package

In your Dart file, import the http package:

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

Step 3: Construct a URL with query parameters using the Uri class

You can use the Uri class to construct a URL with query parameters. This avoids manually concatenating strings and reduces the risk of errors.

dart
var uri = Uri.https('www.example.com', '/search', {'query': 'dart', 'page': '1'});

Here, Uri.https takes the first parameter as the domain, the second as the path, and the third as a Map representing the query parameters.

Step 4: Send the HTTP request

Use the constructed uri to send the HTTP request:

dart
var response = await http.get(uri); if (response.statusCode == 200) { print('Response body: ${response.body}'); } else { print('Request failed with status: ${response.statusCode}.'); }

In this example, we send a GET request to www.example.com/search with the query parameters query=dart and page=1. Then, we check the response status code and print the response content or error message.

Complete Example:

The following is a complete example demonstrating how to construct a request with query parameters and send it:

dart
import 'package:http/http.dart' as http; void main() async { var uri = Uri.https('www.example.com', '/search', {'query': 'dart', 'page': '1'}); var response = await http.get(uri); if (response.statusCode == 200) { print('Response body: ${response.body}'); } else { print('Request failed with status: ${response.statusCode}.'); } }

Using the Uri class helps manage URLs and their query parameters more safely and conveniently, especially when dealing with multiple parameters or requiring URL encoding. This approach avoids errors that could arise from manually concatenating strings.

2024年8月5日 02:07 回复

你的答案