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'); 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 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) { 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 is: application / x-www-form-urlencoded; Charset = UTF-8, that is, it is submitted in form by default.
In this case, for the data that carries 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. We can see from the code that 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 and 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)?})
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, 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. });
summary
Using HttpRequest can directly simulate Ajax operations 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 find!