Detailed implementation of fluent HTTP network request

Time:2021-12-3

HTTP network request is a common and important function in a development language. It is mainly used for resource access, interface data request and submission, uploading and downloading files, etc. HTTP request methods mainly include: get, post, head, put, delete, trace, connect and options. This article focuses on the usage of get and post, two common requests, in fluent, and post will be emphasized. The implementation of HTTP network requests of flutter is mainly divided into three types: the implementation of httpclient in io.dart, the implementation of dart native HTTP request library and the implementation of third-party library. Later, we will explain these differences and characteristics and the use methods of the first two in detail. Next, let’s start the detailed explanation of flutter’s HTTP network request.

This article will mainly introduce:

  • Briefly introduce these HTTP request modes
  • Differences and characteristics of three kinds of HTTP network request implementation in fluent
  • Httpclient implements HTTP network request
  • The native HTTP request Library of dart implements HTTP network requests
  • Recommendations for third-party libraries

1. Introduction to HTTP request mode

HTTP network request mode describes the operation that the client wants to perform on the specified resource or server. As described in the introduction at the beginning, HTTP network request is a common and important function in a development language. It is mainly used for resource access, interface data request and submission, uploading and downloading files, etc. The main request methods include: get, post, head, put, delete, trace, connect and options. Next, briefly introduce their characteristics and functions.

1.1 get request method

It can also be seen from the word get that it mainly performs the operation of obtaining resources. For example, it obtains the returned resources from the server through the URL. Get can splice some parameter information of the request on the URL and pass it to the server. The server side parses the parameter information, and then returns the corresponding resources to the requester. Note: there is a maximum limit on the size and length of URL data spliced by get requests, and the amount of data transmitted is generally limited to 2KB.

1.2 post request mode

Post is mainly used to submit and transmit information. Post requests can carry a lot of data with unlimited format. Such as JSON, XML, text, etc. Moreover, some data and parameters passed by post are not directly spliced after the URL, but placed in the HTTP request body, which is safer than get. And the size and format of the transmitted data are unlimited. Post request is an important and commonly used method. Post request consists of two parts: request header and request body. There are three types of common request bodies for post requests: application / x-www-form-urlencoded, application / JSON, multipart / form data, and of course there are other types, but they are not commonly used. These three types are commonly used.

1.3 head request mode

Head is mainly used to return header information to the requested client instead of body content. It is similar to the get method, except that the get method returns the body entity, while the head only returns the header information and no body entity content. It is mainly used to confirm the validity of the URL, the date and time of resource update, view the server status, etc. for requests requiring this, it does not occupy resources.

1.4 put request mode

Put is mainly used to transfer files, which is similar to FTP file upload. The request contains the file content and saves the file to the server location specified by the URI. The main difference between the put request mode and the post mode is that if the two requests are the same, the latter request will overwrite the previous request, realizing the modification resources of the put mode; In the post request mode, if the two requests are the same, the latter request will not overwrite the previous request, realizing the increase of post resources.

1.5 delete request mode

Delete is mainly used to tell the server to delete the resources and delete the specified resources.

1.6 options request mode

Options is mainly used to query the request methods supported by the server for the URI resource to be requested, that is, to obtain the request methods submitted by the client to the server by the URI.

1.7 trace request mode

Trace is mainly used to track the transmission path. For example, we initiate an HTTP request, which may go through many paths and processes. Trace tells the server to return a response message after receiving the request and return the original HTTP request information it received to the client, In this way, you can confirm whether the request has been modified during HTTP transmission.

1.8 connect request mode

Connect is mainly used to perform connection agent operations, such as “wall climbing”. The client establishes a communication tunnel with the server through connect for TCP communication. It mainly transmits data securely through SSL and TLS. The function of connect is to tell the server to request access to a resource instead of the client, and then return the data to the client, which is equivalent to a media relay.

2. Differences and characteristics of the implementation of the network request of the shuttle http

After introducing several HTTP requests, let’s take a look at the implementation of HTTP network requests in fluent. The implementation of HTTP network requests of flutter is mainly divided into three types: the implementation of httpclient in io.dart, the implementation of dart native HTTP request library and the implementation of third-party library.

Let’s first look at the first: the implementation of httpclient in io.dart.

The HTTP network request implemented by httpclient in io.dart mainly implements the basic network request, and the complex network request cannot be completed. For example, several other body request body transmission content types in post cannot be supported, and multipart / form data transmission is not supported. Therefore, if some of your HTTP network requests can be implemented through the httpclient in io.dart, you can also use this to complete the requirements.
Next, let’s look at the implementation steps of HTTP network request implemented by httpclient in io.dart.

import 'dart:convert';
import 'dart:io';

class IOHttpUtils {
  //Create httpclient
  HttpClient _httpClient = HttpClient();

  //To make an asynchronous request with the async keyword
  getHttpClient() async {
    _httpClient
        .get('https://abc.com', 8090, '/path1')
        .then((HttpClientRequest request) {
      //Here, you can add headers to the request, write the request object data, and so on
      // Then call close.
      return request.close();
    }).then((HttpClientResponse response) {
      //Process response response
      if (response.statusCode == 200) {
        response.transform(utf8.decoder).join().then((String string) {
          print(string);
        });
      } else {
        print("error");
      }
    });
  }

  getUrlHttpClient() async {
    var url = "https://abc.com:8090/path1";
    _httpClient.getUrl(Uri.parse(url)).then((HttpClientRequest request) {
      // Optionally set up headers...
      // Optionally write to the request object...
      // Then call close.
      return request.close();
    }).then((HttpClientResponse response) {
      // Process the response.
      if (response.statusCode == 200) {
        response.transform(utf8.decoder).join().then((String string) {
          print(string);
        });
      } else {
        print("error");
      }
    });
  }

  //Make a post request
  postHttpClient() async {
    _httpClient
        .post('https://abc.com', 8090, '/path2')
        .then((HttpClientRequest request) {
      //The contenttype and content of the post request body are added here
      //This is the transmission mode of application / JSON data type
      request.headers.contentType = ContentType("application", "json");
      request.write("{\"name\":\"value1\",\"pwd\":\"value2\"}");
      return request.close();
    }).then((HttpClientResponse response) {
      // Process the response.
      if (response.statusCode == 200) {
        response.transform(utf8.decoder).join().then((String string) {
          print(string);
        });
      } else {
        print("error");
      }
    });
  }

  postUrlHttpClient() async {
    var url = "https://abc.com:8090/path2";
    _httpClient.postUrl(Uri.parse(url)).then((HttpClientRequest request) {
      //The contenttype and content of the post request body are added here
      //This is the transmission mode of application / x-www-form-urlencoded data type
      request.headers.contentType =
          ContentType("application", "x-www-form-urlencoded");
      request.write("name='value1'&pwd='value2'");
      return request.close();
    }).then((HttpClientResponse response) {
      // Process the response.
      if (response.statusCode == 200) {
        response.transform(utf8.decoder).join().then((String string) {
          print(string);
        });
      } else {
        print("error");
      }
    });
  }

  ///The usage of other head, put and delete requests is similar and similar. You can try it yourself
  ///After successfully requesting data in the widget, use setstate to update the content and status
  ///setState(() {
  ///    ...
  ///  });

}

The second is the implementation of dart native HTTP request library.

This method is recommended here. After all, dart’s native HTTP request library supports more comprehensive HTTP requests, and more complex requests can be implemented, such as uploading and downloading files.

At present, dart’s official warehouse has a large number of third-party libraries and official libraries, which are also very convenient for reference. The official address of dart pub is: https://pub.dartlang.org 。
After opening, see the following figure:

Dart PUB仓库

To use dart native HTTP libraries, we first need to reference the relevant HTTP libraries in dart pub or official GitHub.
Search HTTP in dart pub to find our HTTP library, and reference and use it according to the instructions.
The official GitHub library address of HTTP library is: https://github.com/dart-lang/http

http库

Click installing to view the reference method for reference.

引用http库

Add a reference to the pubspec.yaml configuration file of the project:

加入引用http库

After that, you can directly import in the dart file class. Next, give a complete use example:

import 'dart:convert';
import 'dart:io';

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

class DartHttpUtils {
  //Create client instance
  var _client = http.Client();

  //Send get request
  getClient() async {
    var url = "https://abc.com:8090/path1?name=abc&pwd=123";
    _client.get(url).then((http.Response response) {
      //Processing response information
      if (response.statusCode == 200) {
        print(response.body);
      } else {
        print('error');
      }
    });
  }

//Send post request, application / x-www-form-urlencoded
  postUrlencodedClient() async {
    var url = "https://abc.com:8090/path2";
    //Set header
    Map<String, String> headersMap = new Map();
    headersMap["content-type"] = "application/x-www-form-urlencoded";
    //Set the body parameter
    Map<String, String> bodyParams = new Map();
    bodyParams["name"] = "value1";
    bodyParams["pwd"] = "value2";
    _client
        .post(url, headers: headersMap, body: bodyParams, encoding: Utf8Codec())
        .then((http.Response response) {
      if (response.statusCode == 200) {
        print(response.body);
      } else {
        print('error');
      }
    }).catchError((error) {
      print('error');
    });
  }

  //Send post request, application / JSON
  postJsonClient() async {
    var url = "https://abc.com:8090/path3";
    Map<String, String> headersMap = new Map();
    headersMap["content-type"] = ContentType.json.toString();
    Map<String, String> bodyParams = new Map();
    bodyParams["name"] = "value1";
    bodyParams["pwd"] = "value2";
    _client
        .post(url,
            headers: headersMap,
            body: jsonEncode(bodyParams),
            encoding: Utf8Codec())
        .then((http.Response response) {
      if (response.statusCode == 200) {
        print(response.body);
      } else {
        print('error');
      }
    }).catchError((error) {
      print('error');
    });
  }

  //Send post request, multipart / form data
  postFormDataClient() async {
    var url = "https://abc.com:8090/path4";
    var client = new http.MultipartRequest("post", Uri.parse(url));
    client.fields["name"] = "value1";
    client.fields["pwd"] = "value2";
    client.send().then((http.StreamedResponse response) {
      if (response.statusCode == 200) {
        response.stream.transform(utf8.decoder).join().then((String string) {
          print(string);
        });
      } else {
        print('error');
      }
    }).catchError((error) {
      print('error');
    });
  }

//Send post request, multipart / form data,上传文件
  postFileClient() async {
    var url = "https://abc.com:8090/path5";
    var client = new http.MultipartRequest("post", Uri.parse(url));
    http.MultipartFile.fromPath('file', 'sdcard/img.png',
            filename: 'img.png', contentType: MediaType('image', 'png'))
        .then((http.MultipartFile file) {
      client.files.add(file);
      client.fields["description"] = "descriptiondescription";
      client.send().then((http.StreamedResponse response) {
        if (response.statusCode == 200) {
          response.stream.transform(utf8.decoder).join().then((String string) {
            print(string);
          });
        } else {
          response.stream.transform(utf8.decoder).join().then((String string) {
            print(string);
          });
        }
      }).catchError((error) {
        print(error);
      });
    });
  }
  ///The usage of other head, put and delete requests is similar and similar. You can try it yourself
  ///After successfully requesting data in the widget, use setstate to update the content and status
  ///setState(() {
  ///    ...
  ///  });
}

The third is the implementation of the third-party library.

There are many flutter third-party libraries that can implement HTTP network requests, such as the DIO library developed by domestic developers. DIO supports complex operations such as multiple file upload, file download and concurrent requests. You can search for DIO on dart pub.

引用dio库

Add a reference to the pubspec.yaml configuration file of the project:


dependencies:
  dio: ^2.0.14

In this way, you can reference Dio’s API library to implement HTTP network requests. Give a complete example of DIO usage:

import 'dart:io';

import 'package:dio/dio.dart';

class DartHttpUtils {
  //Configure DIO through baseoptions
  Dio _dio = Dio(BaseOptions(
      baseUrl: "https://abc.com:8090/",
      connectTimeout: 5000,
      receiveTimeout: 5000));

  //Get request for Dio
  getDio() async {
    var url = "/path1?name=abc&pwd=123";
    _dio.get(url).then((Response response) {
      if (response.statusCode == 200) {
        print(response.data.toString());
      }
    });
  }

  getUriDio() async {
    var url = "/path1?name=abc&pwd=123";
    _dio.getUri(Uri.parse(url)).then((Response response) {
      if (response.statusCode == 200) {
        print(response.data.toString());
      }
    }).catchError((error) {
      print(error.toString());
    });
  }

//Get request for Dio,通过queryParameters配置传递参数
  getParametersDio() async {
    var url = "/path1";
    _dio.get(url, queryParameters: {"name": 'abc', "pwd": 123}).then(
        (Response response) {
      if (response.statusCode == 200) {
        print(response.data.toString());
      }
    }).catchError((error) {
      print(error.toString());
    });
  }

//Send post request, application / x-www-form-urlencoded
  postUrlencodedDio() async {
    var url = "/path2";
    _dio
        .post(url,
            data: {"name": 'value1', "pwd": 123},
            options: Options(
                contentType:
                    ContentType.parse("application/x-www-form-urlencoded")))
        .then((Response response) {
      if (response.statusCode == 200) {
        print(response.data.toString());
      }
    }).catchError((error) {
      print(error.toString());
    });
  }

  //Send post request, application / JSON
  postJsonDio() async {
    var url = "/path3";
    _dio
        .post(url,
            data: {"name": 'value1', "pwd": 123},
            options: Options(contentType: ContentType.json))
        .then((Response response) {
      if (response.statusCode == 200) {
        print(response.data.toString());
      }
    }).catchError((error) {
      print(error.toString());
    });
  }

  //Send post request, multipart / form data
  postFormDataDio() async {
    var url = "/path4";
    FormData _formData = FormData.from({
      "name": "value1",
      "pwd": 123,
    });
    _dio.post(url, data: _formData).then((Response response) {
      if (response.statusCode == 200) {
        print(response.data.toString());
      }
    }).catchError((error) {
      print(error.toString());
    });
  }

  //Send post request, multipart / form data,上传文件
  postFileDio() async {
    var url = "/path5";
    FormData _formData = FormData.from({
      "description": "descriptiondescription",
      "file": UploadFileInfo(File("./example/upload.txt"), "upload.txt")
    });
    _dio.post(url, data: _formData).then((Response response) {
      if (response.statusCode == 200) {
        print(response.data.toString());
      }
    }).catchError((error) {
      print(error.toString());
    });
  }

  //Dio download file
  downloadFileDio() {
    var urlPath = "https://abc.com:8090/";
    var savePath = "./abc.html";
    _dio.download(urlPath, savePath).then((Response response) {
      if (response.statusCode == 200) {
        print(response.data.toString());
      }
    }).catchError((error) {
      print(error.toString());
    });
  }

  ///The usage of other head, put and delete requests is similar and similar. You can try it yourself
  ///After successfully requesting data in the widget, use setstate to update the content and status
  ///setState(() {
  ///    ...
  ///  });
}

Well, the detailed explanation of flutter’s HTTP network request will be explained here.

This is the end of this article about the detailed implementation of flutter HTTP network requests. For more information about flutter HTTP network requests, please search the previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!