Dart series: Dancers in browsers use dart to send HTTP requests


brief introduction

Dart: the HTML package provides dart with some necessary components for building the browser client. We mentioned the operations of HTML and DOM before. In addition, another common operation on the browser side is to use XMLHttpRequest to make asynchronous HTTP resource requests, that is, AJAX requests.

Dart also provides a package similar to XMLHttpRequest in JS, and its corresponding class is called httprequest. Let’s see how to use httprequest in dart.

Send get request

Although modern web app is encapsulated by various frameworks, it is still a rich Ajax client application in the final analysis. We request data from the server through various asynchronous HTTP requests, and then display it on the page. Generally speaking, the data interaction format is JSON. Of course, there can be other data interaction formats.

The most common method in AJAX is to send a get request to the server. The corresponding httprequest has a getString method:

  static Future<String> getString(String url,
      {bool? withCredentials, void onProgress(ProgressEvent e)?}) {
    return request(url,
            withCredentials: withCredentials, onProgress: onProgress)
        .then((HttpRequest xhr) => xhr.responseText!);

Note that the getString method is a class method, so you can directly use the httprequest class to call:

var name = Uri.encodeQueryComponent('John');
        var id = Uri.encodeQueryComponent('42');
          .then((String resp) {
            // Do something with the response.

Because getString returns a future, you can directly follow the then statement after getString to obtain the returned value.

Of course, you can also use await in async method to get the return value.

Future<void> main() async {
  String pageHtml = await HttpRequest.getString(url);
  // Do something with pageHtml...

Or use try catch to catch exceptions:

try {
  var data = await HttpRequest.getString(jsonUri);
  // Process data...
} catch (e) {
  // Handle exception...

Send post request

Get is to pull data from the server, and the corresponding post is a general method to submit data to the server. In httprequest, the corresponding method is postformdata:

static Future<HttpRequest> postFormData(String url, Map<String, String> data,
      {bool? withCredentials,
      String? responseType,
      Map<String, String>? requestHeaders,
      void onProgress(ProgressEvent e)?}) {
    var parts = [];
    data.forEach((key, value) {
    var formData = parts.join('&');

    if (requestHeaders == null) {
      requestHeaders = <String, String>{};
        () => 'application/x-www-form-urlencoded; charset=UTF-8');

    return request(url,
        method: 'POST',
        withCredentials: withCredentials,
        responseType: responseType,
        requestHeaders: requestHeaders,
        sendData: formData,
        onProgress: onProgress);

From the implementation of the method, we can see that the content type used by default is: application / x-www-form-urlencoded; Charset = UTF-8, that is, it is submitted in form by default.

In this case, for the data carrying the data, the URI will be performed first Encodequerycomponent, and then use & to connect.

The following is an example:

var data = { 'firstName' : 'John', 'lastName' : 'Doe' };
        HttpRequest.postFormData('/send', data).then((HttpRequest resp) {
          // Do something with the response.

Note that an httprequest is returned in postformdata. Although it is called request, it can actually contain the content of response. So you can directly use it to get the returned content.

More general operation

We explained the post of get and form above. From the code, we can see that they actually call the request method at the bottom. Request is a more general HTTP request method. Can supportPOST, PUT, DELETEWait for HTTP operations. The following is the method definition of request:

  static Future<HttpRequest> request(String url,
      {String? method,
      bool? withCredentials,
      String? responseType,
      String? mimeType,
      Map<String, String>? requestHeaders,
      void onProgress(ProgressEvent e)?})

SendData can be in the format of [ByteBuffer], [blob], [document], [string], or [formdata].

Responsetype indicates httprequest Responsetype is the format of the returned object. By default, it is string. It can also be ‘arraybuffer’, ‘blob’, ‘document’, ‘JSON’, or ‘text’.

The following is an example of using request directly:

        var myForm = querySelector('form#myForm');
        var data = new FormData(myForm);
        HttpRequest.request('/submit', method: 'POST', sendData: data)
          .then((HttpRequest resp) {
            // Do something with the response.


Using httprequest can directly simulate Ajax operations in the browser, which is very convenient.

This article has been included inhttp://www.flydean.com/21-dart-http/

The most popular interpretation, the most profound dry goods, the most concise tutorial, and many tips you don’t know are waiting for you to find!

Welcome to my official account: “procedures and things”. I understand technology and you better!