Introduction

The dart:html package provides dart with some necessary components for building the browser client. We mentioned the operation of HTML and DOM before. In addition to these, another common operation on the browser side is to use XMLHttpRequest to do asynchronous HTTP. Requests for resources are AJAX requests.

Dart also provides a package similar to XMLHttpRequest in JS, and its corresponding class is called HttpRequest. Let's take a look at how to use HttpRequest in dart.

Send GET request

Although modern web APP is encapsulated by various frameworks, it is still an AJAX rich 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, other data interaction formats are also possible.

The most commonly used 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 use the HttpRequest class directly to call:

var name = Uri.encodeQueryComponent('John');
        var id = Uri.encodeQueryComponent('42');
        HttpRequest.getString('users.json?name=$name&id=$id')
          .then((String resp) {
            // Do something with the response.
        });

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

Of course, you can also use await in the 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 the exception:

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 of submitting 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) {
      parts.add('${Uri.encodeQueryComponent(key)}='
          '${Uri.encodeQueryComponent(value)}');
    });
    var formData = parts.join('&');

    if (requestHeaders == null) {
      requestHeaders = <String, String>{};
    }
    requestHeaders.putIfAbsent('Content-Type',
        () => '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: application/x-www-form-urlencoded; charset=UTF-8, which means that the default is in the form of form submission.

In this case, for the data that carries the data, the Uri.encodeQueryComponent will be encoded first, and then the & will be used to connect.

The following is an example of use:

var data = { 'firstName' : 'John', 'lastName' : 'Doe' };
        HttpRequest.postFormData('/send', data).then((HttpRequest resp) {
          // Do something with the response.
       });
Note that what is returned in postFormData is an HttpRequest. Although it is called Request, it can actually contain the content of the response. So use it directly to get the returned content.

More general operation

Above we explained the post of get and form. As you can see from the code, they actually call the request method at the bottom. request is a more general HTTP request method. It can support HTTP operations such as POST , PUT , DELETE 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,
      sendData,
      void onProgress(ProgressEvent e)?})

The sendData can be in the format of [ByteBuffer], [Blob], [Document], [String], or [FormData].

responseType represents HttpRequest.responseType, which is the format of the returned object. By default, it is String, or it can 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.
        });

Summarize

Using HttpRequest can directly simulate the Ajax operation in the browser, which is very convenient.

This article has been included in http://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 discover!

Welcome to pay attention to my official account: "Program those things", know the technology, know you better!


flydean
890 声望437 粉丝

欢迎访问我的个人网站:www.flydean.com