flutter 自己封装一个简单的http请求

337 阅读1分钟

我们使用dart语言自带的请求,这样如果要做服务端也可以拿来使用

简单配置,支持MOCK数据,支持post

http.dart

import 'dart:io';
import 'dart:async';
import 'dart:convert';
import './config.dart';

Future<String> HTTP(String path, Map<String, dynamic> queryParameters) async{
  return new Future(() async{
    if(CONFIG.HTTP_MOCK){
      print('正在只在模拟请求,请求路径为:$path');
      switch(path){
        case 'getxhsalxbsahomexsajkxblist':{
          String response = '''  ''';
          return response;
        }
        case 'getxsavioxsachaterhgjkgliost':{
          String response = '''  ''';
          return response;
        }
        case 'get_vxsaeoxaschterxsaxsano':{
          String response = '''  ''';
          return response;
        }
        default :{
          print('没匹配到api地址');
          return '';
        }
      }
    }
    HttpClient httpClient = new HttpClient();
    HttpClientRequest request;
    
    // POST
    request = await httpClient.postUrl(
      // queryParameters: queryParameters
      Uri(scheme: "http", host: CONFIG.BaseHost, path: path, port: 9001)
    );
    request.headers.add('Accept', 'application/json, text/plain, */*');
    request.headers.add('Content-Type', 'application/json;charset=UTF-8');
    String payload = jsonEncode(queryParameters);
    request.add(utf8.encode(payload));
    HttpClientResponse response = await request.close();
    // print(response);
    if (response.statusCode == HttpStatus.ok) {
        String  _content = await response.transform(Utf8Decoder()).join();
        return _content;
    }
  });
}

config配置文件

class CONFIG {
  static bool HTTP_MOCK = false;
  static String BaseHost = "192.168.0.111";
}

use

HTTP类型

Future<String> HTTP(String path, Map<String, dynamic> queryParameters)

使用例子

String response_content = await HTTP('get_vxsaeoxaschterxsaxsano', {"id": id.toString()});

这个远远不能满足生产需求,之后我们再进行改进


有了请求数据后我们就需要读取和解析,下一篇讲json解析和模型类(model class)

--END--