There are three ways that Flutter requests the network

Dart’s native Web request HttpClient, third-party web request HTTP, and Dio in FLUTTER can be used to request networks. We can compare these three types of network requests and encapsulate them into a utility class that facilitates our network requests.

Dart’s native web request HttpClient

Dart requests to obtain network data generally require the following steps:

  • The pubspec.yaml file does not need to be modified for native web requests. We simply import the required package where it is used
import 'dart:convert';
import 'dart:io';
Copy the code
  • Step 2: Create an HttpClient
HttpClient httpClient = new HttpClient();
Copy the code
  • Step 3: Open the Http connection and set the request header
HttpClientRequest request = await httpClient.getUrl(uri);
Copy the code

In this step, we can set up the desired request methods, such as Get request, Post request, and Delete request.

For example, a request with parameters

Uri uri=Uri(scheme: "https", host: "flutterchina.club", queryParameters: {
    "userName":"chen"."password":"123456"
  });
Copy the code

For example, set the header of the request

request.headers.add("user-agent"."test");
request.headers.add("Authorization"."LKSJDLFJSDLKJSLKklsdj");
Copy the code
  • Step 4: Wait to connect to the server
HttpClientResponse response = await request.close();
Copy the code
  • Step 5: Read the response content
if (response.statusCode == HttpStatus.ok) {
      _content = await response.transform(Utf8Decoder()).join();
}
Copy the code
  • Step 6: Disconnect
httpClient.close();
Copy the code

Dart is a simple way to obtain the network. As you can see from the above, it is difficult to initiate a network request through HttpClient, many of which need to be handled by ourselves, as well as the management of cookies.

Library HTTP

  • Step 1: Pubspec. yaml Add dependencies
http: '> = 0.11.3 + 12'
Copy the code
  • Step 2: Guide the bag where it is used
import 'package:http/http.dart' as http;
Copy the code
  • Step 3: Initiate a request

A Get request

void getRequest() async {
    var client = http.Client();
    http.Response response = await client.get(url_2);
    _content = response.body;
  }
Copy the code

A Post request

  void postRequest() async {
    var params = Map<String, String>();
    params["username"] = "hellonews";
    params["password"] = "123456";

    var client = http.Client();
    var response = await client.post(url_post, body: params);
    _content = response.body;
  }
Copy the code

Compared to Dart’s native web request, the third-party library HTTP web request is a lot easier and easier to write.

Dio published by Flutter

Dio a powerful Dart Http request library with support for Restful apis, FormData, interceptors, request cancellation, Cookie management, file upload/download, timeouts…

  • Step 1: Pubspec. yaml Add dependencies
Dependencies: dio: ^ 1.0.9Copy the code
  • Step 2: Import the reference package
import 'package:dio/dio.dart';
Copy the code
  • Step 3: Initiate a network request

A Get request

void getRequest() async {
    Dio dio = new Dio();
    var response = await dio.get("/test? id=12&name=chen");
    _content = response.data.toString();
  }
Copy the code

For the query argument, we can pass it through an object. The above code is equivalent to:

void getRequest() async {
    Dio dio = new Dio();
    var response = await dio.get("/test", data: {"id": 12."name":"chen"});
    _content = response.data.toString();
  }
Copy the code

A Post request

  void postRequest() async {
    var dio = new Dio();
    var response = await dio.post(url_post, data:{"id": 12."name":"wendu"});
    _content = response.data.toString();
  }
Copy the code

Dio Network request framework encapsulation

Log Interception

Dio, like OKHTTP, has a request interceptor and a response interceptor, through which we can do some pre-processing of consent before or after a request or response. For example, we can see the parameters and headers of our request before making a request, and when we respond, we can see the data that comes back.

Dio dio = new Dio(); // Add interceptorif (Config.DEBUG) {
      dio.interceptors.add(InterceptorsWrapper(
          onRequest: (RequestOptions options){
            print("\ n = = = = = = = = = = = = = = = = = = request data = = = = = = = = = = = = = = = = = = = = = = = = = =");
            print("url = ${options.uri.toString()}");
            print("headers = ${options.headers}");
            print("params = ${options.data}");
          },
          onResponse: (Response response){
            print("\ n = = = = = = = = = = = = = = = = = = response data = = = = = = = = = = = = = = = = = = = = = = = = = =");
            print("code = ${response.statusCode}");
            print("data = ${response.data}");
            print("\n");
          },
          onError: (DioError e){
            print("\ n = = = = = = = = = = = = = = = = = = error response data = = = = = = = = = = = = = = = = = = = = = =");
            print("type = ${e.type}");
            print("message = ${e.message}");
            print("stackTrace = ${e.stackTrace}");
            print("\n"); })); }Copy the code

If we want to remove the interceptor, we can set it to NULL

dio.interceptor.request.onSend=null;
dio.interceptor.response.onSuccess=null;
dio.interceptor.response.onError=null;
Copy the code

Token to add

// add a token to verify headers["Authorization"] = "token lskjdlklsjkdklsjd333"; option.headers = headers; /// Timeout option.connectTimeout = 15000; try { Response response = await dio.request(url, data: params, options: option); } on DioError catch (e) {Copy the code

FlutterJsonBeanFactory automatically generates dart’s JSON entity class

In Android development, there is the GsonFormat plug-in to automatically convert JSON data into beans; There is a similar plugin for Flutter that produces serialized entity classes: FlutterJsonBeanFactory

  • Step 1: Download the plug-in FlutterJsonBeanFactory and restart after installation
Setting -> Plugins -> Browse Respositories search FlutterJsonBeanFactoryCopy the code
  • Step 2: Create the entity class in the specified directory:
New -> dart bean class File from JSON
Copy the code

  • Step 3: Enter the entity class name and data in JSON format

  • Step 4: The last generated entity class is LoginEntity

class LoginEntity {
	String easemobpassword;
	String username;

	LoginEntity({this.easemobpassword, this.username});

	LoginEntity.fromJson(Map<String, dynamic> json) {
		easemobpassword = json['easemobPassword'];
		username = json['username'];
	}

	Map<String, dynamic> toJson() {
		final Map<String, dynamic> data = new Map<String, dynamic>();
		data['easemobPassword'] = this.easemobpassword;
		data['username'] = this.username;
		returndata; }}Copy the code

Request error handling

Response response; try { response = await dio.request(url, data: params, options: option); } on DioError catch (e) {errorResponse;if(e.response ! = null) { errorResponse = e.response; }else {
        errorResponse = new Response(statusCode: 666);
      }
      if (e.type == DioErrorType.CONNECT_TIMEOUT) {
        errorResponse.statusCode = Code.NETWORK_TIMEOUT;
      }
      if (Config.DEBUG) {
        print('Request exception:' + e.toString());
        print('Request exception URL:' + url);
      }
      return new ResultData(Code.errorHandleFunction(errorResponse.statusCode, e.message, noTip), false, errorResponse.statusCode);
    }
Copy the code

ResultData is the entity class for network result processing

/** * Created by chenjianrun * Date: 2018-07-16 */ class ResultData {var data; bool result; int code; var headers; ResultData(this.data, this.result, this.code, {this.headers}); }Copy the code

Code is the Code that handles network errors and sends the error results via eventBus, which we can register to listen for in main_pager.

Static const NETWORK_ERROR = -1; static const NETWORK_ERROR = -1; // Network timeout static const NETWORK_TIMEOUT = -2; Static const NETWORK_JSON_EXCEPTION = -3; static const SUCCESS = 200; static final EventBus eventBus = new EventBus(); static errorHandleFunction(code, message, noTip) {if(noTip) {
      return message;
    }
    eventBus.fire(new HttpErrorEvent(code, message));
    returnmessage; }}Copy the code

Completed network request class: HttpRequest

import 'dart:io';

import 'package:dio/dio.dart';
import 'package:private_tutor/common/SpUtils.dart';
import 'package:connectivity/connectivity.dart';

import 'dart:collection';

import 'package:private_tutor/common/config/Config.dart';
import 'package:private_tutor/net/ResultCode.dart';
import 'package:private_tutor/net/ResultData.dart'; Class HttpRequest {static String _baseUrl; static const CONTENT_TYPE_JSON ="application/json";
  static const CONTENT_TYPE_FORM = "application/x-www-form-urlencoded";
  static Map optionParams = {
    "timeoutMs": 15000,
    "token": null,
    "authorizationCode": null,
  };

  static setBaseUrl(String baseUrl){
    _baseUrl = baseUrl;
  }

  static get(url,param) async{
    return await request(_baseUrl+url, param, null, new Options(method:"GET"));
  }

  static post(url,param) async{
    return await request(_baseUrl+url, param, {"Accept": 'application/vnd.github.VERSION.full+json'}, new Options(method: 'POST'));
  }

  static delete(url,param) async{
    return await request(_baseUrl+url, param, null, new Options(method: 'DELETE'));
  }

  static put(url,param) async{
    return await request(_baseUrl+url, param, null, new Options(method: "PUT", contentType: ContentType.text)); } static request(url, params, Map<String, params, Map<String, params, Map<String, params, Map<String, String> header, Options option, {noTip =false}) async {// No network var connectivityResult = await (new Connectivity().checkconnectivity ());if (connectivityResult == ConnectivityResult.none) {
      return new ResultData(Code.errorHandleFunction(Code.NETWORK_ERROR, "", noTip), false, Code.NETWORK_ERROR);
    }

    Map<String, String> headers = new HashMap();
    if(header ! = null) { headers.addAll(header); } // Authorization codeif (optionParams["authorizationCode"] == null) {
      var authorizationCode = await getAuthorization();
      if(authorizationCode ! = null) { optionParams["authorizationCode"] = authorizationCode;
      }
    }

    headers["Authorization"] = optionParams["authorizationCode"]; / / set the baseUrlif(option ! = null) { option.headers = headers; }else{
      option = new Options(method: "get"); option.headers = headers; } /// timeout option.connectTimeout = 15000; Dio dio = new Dio(); // Add interceptorif (Config.DEBUG) {
      dio.interceptors.add(InterceptorsWrapper(
          onRequest: (RequestOptions options){
            print("\ n = = = = = = = = = = = = = = = = = = request data = = = = = = = = = = = = = = = = = = = = = = = = = =");
            print("url = ${options.uri.toString()}");
            print("headers = ${options.headers}");
            print("params = ${options.data}");
          },
          onResponse: (Response response){
            print("\ n = = = = = = = = = = = = = = = = = = response data = = = = = = = = = = = = = = = = = = = = = = = = = =");
            print("code = ${response.statusCode}");
            print("data = ${response.data}");
            print("\n");
          },
          onError: (DioError e){
            print("\ n = = = = = = = = = = = = = = = = = = error response data = = = = = = = = = = = = = = = = = = = = = =");
            print("type = ${e.type}");
            print("message = ${e.message}");
            print("stackTrace = ${e.stackTrace}");
            print("\n"); })); } Response response; try { response = await dio.request(url, data: params, options: option); } on DioError catch (e) {errorResponse;if(e.response ! = null) { errorResponse = e.response; }else {
        errorResponse = new Response(statusCode: 666);
      }
      if (e.type == DioErrorType.CONNECT_TIMEOUT) {
        errorResponse.statusCode = Code.NETWORK_TIMEOUT;
      }
      if (Config.DEBUG) {
        print('Request exception:' + e.toString());
        print('Request exception URL:' + url);
      }
      return new ResultData(Code.errorHandleFunction(errorResponse.statusCode, e.message, noTip), false, errorResponse.statusCode);
    }

    try {
      if(option.contentType ! = null && option.contentType.primaryType =="text") {
        return new ResultData(response.data, true, Code.SUCCESS);
      } else {
        var responseJson = response.data;
        if (response.statusCode == 201 && responseJson["token"] != null) {
          optionParams["authorizationCode"] = 'token ' + responseJson["token"];
          await SpUtils.save(Config.TOKEN_KEY, optionParams["authorizationCode"]); }}if (response.statusCode == 200 || response.statusCode == 201) {
        return ResultData(response.data, true, Code.SUCCESS, headers: response.headers);
      }
    } catch (e) {
      print(e.toString() + url);
      return ResultData(response.data, false, response.statusCode, headers: response.headers);
    }
    return new ResultData(Code.errorHandleFunction(response.statusCode, "", noTip), false, response.statusCode); } /// Clear authorization staticclearAuthorization() {
    optionParams["authorizationCode"] = null; SpUtils.remove(Config.TOKEN_KEY); } static getAuthorization() async {String token = await sputils.get (config.token_key);if (token == null) {
      String basic = await SpUtils.get(Config.USER_BASIC_CODE);
      if(basic == null) {// Prompt for password}else{// Get the token through Basic, get the Settings, and return the tokenreturn "Basic $basic"; }}else {
      optionParams["authorizationCode"] = token;
      returntoken; }}}Copy the code

Use the sample

Static phoneLogin(String phone,String verifyCode) async{ResultData Response = await HttpRequest.post(Address.phoneLogin, {"phoneNum" : phone,"captcha":verifyCode});
    if(response ! = null && response.result){ PhoneLoginEntity phoneLoginEntity = PhoneLoginEntity.fromJson(json.decode(response.data));return new DataResult(phoneLoginEntity, true);
    }else{
      return new DataResult(null, false); }} static getVerifyCode(String phone) async{ResultData response = await httprequest.get ("${Address.getVerifyCode}? phone=${phone}", null);

//    var response = await HttpRequest.get(Address.getVerifyCode, {"phone":phone});
    if(response ! = null && response.result){ VerifyCodeEntity entity = VerifyCodeEntity.fromJson(response.data);return new DataResult(entity, true);
    }else{
      return new DataResult(null, false); }}}Copy the code

The authors introduce

  • Chen Jianrun: Android development engineer of Guangzhou Reed APP Team

Push the information

  • We are recruiting partners, interested partners can send your resume to [email protected], note: from the nuggets community
  • For details, please click here –> Guangzhou Reed Information Technology