Administrator
Administrator
Published on 2025-06-08 / 6 Visits
0
0

http

请求API、上传文件等

链接:https://pub.dev/packages/http

引入依赖

pubspec.yaml

dependencies:
  http: ^1.4.0
  http_parser: ^4.1.2

get请求

    var response = await http.get(Uri.parse("http://172.18.208.1:8080/get?a=1&b=2"));
    //response类型是Response
    print(response.body); //String
    print(response.bodyBytes); // Uint8List(字节序列)

纯文本

text/plain

  final response2 = await http.post(Uri.parse("http://172.18.208.1:8080/post?a=1&b=2"), body: '纯文本数据');
  //response2类型是Response
  print(response2.body); //String
  print(response2.bodyBytes); // Uint8List(字节序列)

form

body只接收<String,String>,Content-Type:application/x-www-form-urlencoded; charset=utf-8

    final response2 = await http.post(Uri.parse("http://172.18.208.1:8080/post?a=1&b=2"), body: {"a":"1","b":"2"});
    //response2类型是Response
    print(response2.body); //String
    print(response2.bodyBytes); // Uint8List(字节序列)

JSON

  final payload = {
    "a":1,
    "b": "2"
  };
  final response2 = await http.post(Uri.parse("http://172.18.208.1:8080/post?a=1&b=2"), headers: {
    'Content-Type': 'application/json'
  }, body: jsonEncode(payload)); //发送JSON数据
  //response2类型是Response
  print(response2.body); //String
  print(response2.bodyBytes); // Uint8List(字节序列)

formdata

创建请求并填充数据

    var request = http.MultipartRequest(
      "post",
      Uri.parse("http://172.18.208.1:8080/post"),
    );
    request.fields["name"] = "zhangsan"; //string字段

    var buf = Uint8List.fromList([65,66,67]); //假设为txt文件,内容为: ABC
    final file = http.MultipartFile.fromBytes('myFile', buf, filename: "1.txt", contentType: MediaType("text", "plain"));
    request.files.add(file); //添加文件到表单
    var response = await request.send(); //类型:StreamedResponse

StreamedResponse转String方式1

    var response2 = await http.Response.fromStream(response); //转成和.post方法返回的类型一致:Response
    print(response2.body); //String
    print(response2.bodyBytes); //Uint8List

StreamedResponse转String方式2

    var body = await response.stream.transform(utf8.decoder).join(); //String
    print(body);

StreamedResponse转String方式3

    var list = await response.stream.fold<List<int>>(<int>[], (previous, element) => previous..addAll(element)); //扁平化
    print(utf8.decode(list)); // String

单例类实例

class ApiService {
  final http.Client _client = http.Client();


  ApiService._internal();// 私有构造函数
  static final ApiService _instance = ApiService._internal(); //静态私有实例
  factory ApiService(String title) => _instance; // 每次调用构造函数都返回相同实例

  Future<String> fetch() async {
    final data = await _client.get(Uri.parse("http://exam.com/test"));
    return data.body;
  }
}

class _MyHomePageState extends State<MyHomePage> {
  final ApiService _api = ApiService("123");

  void _incrementCounter() async {
    _api.fetch(); //请求数据
  }
}


Comment