This is the 14th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Here I would like to share my thoughts on Flutter network requests

purpose

The goal is simply to complete the normal Http GET and POST requests for server-side interface data in the project to complete part of the presentation logic of the page

plan

There are three main implementation schemes, one is based on native HttpClient to achieve, the other two are based on third-party package to achieve: HTTP and DIO

The original HTTP

Dart: IO library: httpClient

import 'dart:io';

var httpClient = new HttpClient();
Copy the code

The client supports common HTTP operations, such as GET, POST, PUT, and DELETE.

The core steps mainly include:

  • Create a client.
  • Construct the Uri.
  • Initiate a request and wait for the request. You can also configure headers and body requests.
  • Close the request and wait for the response.
  • Decode the contents of the response.

And response needs to be implemented based on Futuers (with await/async function at the same time), similar to JS Promise:

get() async {
  var httpClient = new HttpClient();
  var uri = new Uri.http(
      'example.com', '/path1/path2', {'param1': '42', 'param2': 'foo'});
  var request = await httpClient.getUrl(uri);
  var response = await request.close();
  var responseBody = await response.transform(UTF8.decoder).join();
}
Copy the code

If you want to parse the response in JSON format, you usually need to use the dart:convert library method:

Map data = JSON.decode(responseBody); // Suppose the return body structure is similar: ['foo', {'bar': 499}] int barValue = data[1]['bar']; // Bar Value is set to 499Copy the code

OK, that’s a simple way to use the scheme

HTTP library

The library’s address is: pub.flutter-io.cn/packages/ht…

In a nutshell, this library simplifies Http operations. Details on how to use it and how to use it are listed in the tutorial. Here is a simple example

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

var url = Uri.parse('https://example.com/whatsit/create');
var response = await http.post(url, body: {'name': 'doodle', 'color': 'blue'});
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');

print(await http.read(Uri.parse('https://example.com/foobar.txt')));
Copy the code

My project was relatively simple and ENDED up using the library as an API for network requests

Dio library

The library address of this name is: pub.flutter-io.cn/packages/di…

The library encapsulates the use of httpClient and supports interceptors, global configuration, data formatting, request cancels, file downloads, and more

We suggest that you can give priority to the actual project, library documents and online tutorials are also many, not easy to encounter pits

Finally, add a simplified document: github.com/flutterchin…

import 'package:dio/dio.dart'; void getHttp() async { try { var response = await Dio().get('http://www.google.com'); print(response); } catch (e) { print(e); }}Copy the code

Problems encountered

Network request development process also encountered two small problems, after elimination are now solved, also share with you

The Socket Exception Exception

During the first real machine test, log reported an error similar to the following:

[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: DioError [DioErrorType.other]: SocketException: OS Error: Connection timed out, errno = 110, address = 192.168.xxx.xxx, port = XXXX

I didn’t read the Log carefully at first, thinking there was a problem with the library usage, but I still reported similar problems when switching to the native library, with core SocketExceptions and connection timeouts

But try the real machine is able to network ah, and also tried the network to change the test Host from localhost to the actual IP (local interface test development ing), also useless

Finally found that because the host network and the network of the real machine is not the same local area network caused by, because your computer connected to the real machine debugging will go computer agent, finally adjusted the IP of the real machine to solve ~

The returned data contains Chinese garbled characters

Another problem was that my test data contained Chinese characters, but the Chinese garbled characters were obtained after RES and decode. I immediately thought that the character encoding was not chosen correctly during decode, so the corresponding characters could not be found.

HTTP and jsonDecode: utF-8

final res = json.decode(utf8.decode(response.bodyBytes))
Copy the code

OK, we’re done

review

  • Three ways to implement Flutter network requests
  • Real machine test times a solution to Socket Exception
  • Return part of the Chinese data is garbled causes and solutions