We use dart's built-in HttpClient
to call HTTP API:
HttpClient httpClient = HttpClient(); HttpClientRequest request = await httpClient.getUrl(uri); // ...
But using dio
to do so is much easier. If you are Python developer, thinking this as the built-in urllib
vs the requests
lib. The latter one is much easier to use.
Let's do a quick demo of using thsi dio
package.
1, Create a folder named "diotest", then create the pubspec.yaml
file:
name: diotest environment: sdk: '>=2.10.0 <3.0.0'
2, Install the dio
package:
$ dart pub add dio
3, Create main.dart
and write code like this:
import 'package:dio/dio.dart'; void main() async { BaseOptions options = BaseOptions( baseUrl: "https://httpbin.org", connectTimeout: 3000, receiveTimeout: 3000, ); Dio dio = Dio(options); try { Response resp = await dio.get( "/get", queryParameters: {"search": "dio"}, ); print("Response:"); print("Status:\n${resp.statusCode}"); print("Header:\n${resp.headers}"); print("Data:\n${resp.data}"); } catch (e) { print("Exception: $e"); } }
All set, now just run it:
$ dart main.dart Response: Status: 200 Header: connection: keep-alive access-control-allow-credentials: true date: Fri, 17 Dec 2021 04:50:26 GMT access-control-allow-origin: * content-length: 306 content-type: application/json server: gunicorn/19.9.0 Data: {args: {search: dio}, headers: {Accept-Encoding: gzip, Host: httpbin.org, User-Agent: Dart/2.14 (dart:io), X-Amzn-Trace-Id: Root=1-61bc1712-57909160379aeca870fa551c}, origin: 67.83.137.85, url: https://httpbin.org/get?search=dio}
For more on sending POST / PUT / DELETE / Upload Files, you can just visit the example page
Top comments (0)