http网络请求是一门开发语言里比较常用和重要的功能,主要用于资源访问、接口数据请求和提交、上传下载文件等等操作,http请求方式主要有:get、post、head、put、delete、trace、connect、options。本文主要get和post这两种常用请求在flutter中的用法,其中对post将进行着重讲解。flutter的http网络请求的实现主要分为三种:io.dart里的httpclient实现、dart原生http请求库实现、第三方库实现。后面将会给大家详细讲解这几种区别和特点及前两种的使用方法。接下来,我们就开始flutter的http网络请求详解吧。

本文将主要介绍:

  • 简单介绍这几种http请求方式
  • flutter三种http网络请求实现的区别和特点
  • httpclient实现http网络请求
  • dart原生http请求库实现http网络请求
  • 第三方库的推荐

1. http的请求方式简介

http网络请求方式就是描述了客户端想对指定的资源或服务器所要执行的操作。开头简介里介绍过,http网络请求是一门开发语言里比较常用和重要的功能,主要用于资源访问、接口数据请求和提交、上传下载文件等等操作。其中主要的请求方式有:get、post、head、put、delete、trace、connect、options这八种。接下来先简单介绍它们的特点和作用。

1.1 get请求方式

从get这个单词上也可以看出,它主要是执行获取资源操作的,例如通过url从服务器获取返回的资源,其中get可以把请求的一些参数信息拼接在url上,传递给服务器,由服务器端进行参数信息解析,然后返回相应的资源给请求者。注意:get请求拼接的url数据大小和长度是有最大限制的,传输的数据量一般限制在2kb。

1.2 post请求方式

post主要是执行提交信息、传输信息的操作,post请求的可以携带很多的数据,而且格式不限。如json、xml、文本等等都支持。并且post传递的一些数据和参数不是直接拼接在url后的,而是放在http请求body里,相对get来说比较安全。并且传递的数据大小和格式是无限制的。post请求方式是比较重要和常用的一种,post请求包含两部分:请求头(header)和请求体(body)。post请求常见的请求体(body)有三种传输内容类型content-type:application/x-www-form-urlencoded、application/json、multipart/form-data,当然还有其他的几种,不过不常用,常用的就是这三种。

1.3 head请求方式

head主要是执行给请求的客户端返回头信息,而不返回body主体内容。和get方式类似,只不过get方式有body实体返回,而head只返回头信息,无body实体内容返回。主要是用于确认url的有效性、资源更新的日期时间、查看服务器状态等等,对于有这方面需求的请求来说,比较不占用资源。

1.4 put请求方式

put主要是执行传输文件操作,类似于ftp的文件上传一样,请求里包含文件内容,并将此文件保存到uri指定的服务器位置。和post方式的主要区别是:put请求方式如果前后两个请求相同,则后一个请求会把前一个请求覆盖掉,实现了put方式的修改资源;而post请求方式如果前后两个请求相同,则后一个请求不会把前一个请求覆盖掉,实现了post的增加资源。

1.5 delete请求方式

delete主要是执行告诉服务器想要删除的资源,执行删除指定资源操作。

1.6 options请求方式

options主要是执行查询针对所要请求的uri资源服务器所支持的请求方式,也就是获取这个uri所支持客户端提交给服务器端的请求方式有哪些。

1.7 trace请求方式

trace主要是执行追踪传输路径的操作,例如,我们发起了一个http请求,在这个过程中这个请求可能会经过很多个路径和过程,trace就是告诉服务器在收到请求后,返回一条响应信息,将它收到的原始http请求信息返回给客户端,这样就可以确认在http传输过程中请求是否被修改过。

1.8 connect请求方式

connect主要就是执行连接代理操作,例如“翻墙”。客户端通过connect方式与服务器建立通信隧道,进行tcp通信。主要通过ssl和tls安全传输数据。connect的作用就是告诉服务器让它代替客户端去请求访问某个资源,然后再将数据返回给客户端,相当于一个媒介中转。

2. flutter http网络请求实现的区别和特点

介绍完了http几种请求方式,我们看下flutter中的http网络请求的实现方式。flutter的http网络请求的实现主要分为三种:io.dart里的httpclient实现、dart原生http请求库实现、第三方库实现。

我们首先看下第一种:io.dart里的httpclient实现。

io.dart里的httpclient实现的http网络请求主要是实现了基本的网络请求,复杂一些的网络请求还无法完成。例如post里的其他几种body请求体传输内容类型部分还无法支持,multipart/form-data这个类型传输还不支持。所以如果你的一些http网络请求可以通过io.dart里的httpclient实现的话,用这个也可以完成要求。
那么接下来我们就看下io.dart里的httpclient实现的http网络请求实现步骤。

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

class iohttputils {
  //创建httpclient
  httpclient _httpclient = httpclient();

  //要用async关键字异步请求
  gethttpclient() async {
    _httpclient
        .get('https://abc.com', 8090, '/path1')
        .then((httpclientrequest request) {
      //在这里可以对request请求添加headers操作,写入请求对象数据等等
      // then call close.
      return request.close();
    }).then((httpclientresponse 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");
      }
    });
  }

  //进行post请求
  posthttpclient() async {
    _httpclient
        .post('https://abc.com', 8090, '/path2')
        .then((httpclientrequest request) {
      //这里添加post请求body的contenttype和内容
      //这个是application/json数据类型的传输方式
      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) {
      //这里添加post请求body的contenttype和内容
      //这个是application/x-www-form-urlencoded数据类型的传输方式
      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");
      }
    });
  }

  ///其余的head、put、delete请求用法类似,大同小异,大家可以自己试一下
  ///在widget里请求成功数据后,使用setstate来更新内容和状态即可
  ///setstate(() {
  ///    ...
  ///  });

}

第二种:dart原生http请求库实现。

这里推荐这种方式使用,毕竟dart原生的http请求库支持的http请求比较全面,比较复杂的请求都可以实现,如上传和下载文件等等操作。

dart目前官方的仓库里有大量的三方库和官方库,引用也非常的方便,dart pub官方地址为:https://pub.dartlang.org。
打开后如下图所示:

使用dart原生http库,我们首先需要在dart pub或官方github里把相关的http库引用下来。
在dart pub里搜索http,便可以查找到我们的http库,根据说明进行引用和使用即可。
http库官方github库地址为:

点击installing,查看引用方法进行引用即可。

在项目的pubspec.yaml配置文件里加入引用:

完毕,这样就可以在dart文件类里直接import使用了。接下来给一个完整的使用例子:

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

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

class darthttputils {
  //创建client实例
  var _client = http.client();

  //发送get请求
  getclient() async {
    var url = "https://abc.com:8090/path1?name=abc&pwd=123";
    _client.get(url).then((http.response response) {
      //处理响应信息
      if (response.statuscode == 200) {
        print(response.body);
      } else {
        print('error');
      }
    });
  }

//发送post请求,application/x-www-form-urlencoded
  posturlencodedclient() async {
    var url = "https://abc.com:8090/path2";
    //设置header
    map<string, string> headersmap = new map();
    headersmap["content-type"] = "application/x-www-form-urlencoded";
    //设置body参数
    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');
    });
  }

  //发送post请求,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');
    });
  }

  // 发送post请求,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');
    });
  }

// 发送post请求,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);
      });
    });
  }
  ///其余的head、put、delete请求用法类似,大同小异,大家可以自己试一下
  ///在widget里请求成功数据后,使用setstate来更新内容和状态即可
  ///setstate(() {
  ///    ...
  ///  });
}

第三种:第三方库实现。

flutter第三方库有很多可以实现http网络请求,例如国内开发者开发的dio库,dio支持多个文件上传、文件下载、并发请求等复杂的操作。在dart pub上可以搜索dio。

在项目的pubspec.yaml配置文件里加入引用:

dependencies:
  dio: ^2.0.14

这样就可以引用dio的api库来实现http网络请求了。给一个完整的dio用法例子:

import 'dart:io';

import 'package:dio/dio.dart';

class darthttputils {
  //配置dio,通过baseoptions
  dio _dio = dio(baseoptions(
      baseurl: "https://abc.com:8090/",
      connecttimeout: 5000,
      receivetimeout: 5000));

  //dio的get请求
  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());
    });
  }

//dio的get请求,通过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());
    });
  }

//发送post请求,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());
    });
  }

  //发送post请求,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());
    });
  }

  // 发送post请求,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());
    });
  }

  // 发送post请求,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下载文件
  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());
    });
  }

  ///其余的head、put、delete请求用法类似,大同小异,大家可以自己试一下
  ///在widget里请求成功数据后,使用setstate来更新内容和状态即可
  ///setstate(() {
  ///    ...
  ///  });
}

好了,flutter的http网络请求详解就为大家讲解到这里。

到此这篇关于flutter http网络请求实现详解的文章就介绍到这了,更多相关flutter http网络请求内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!