欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Flutter网络请求的3种简单实现方法

程序员文章站 2023-09-04 08:52:32
概述: app几乎都离不开与服务器的交互,本文主要讲解了flutter网络请求三种方式 flutter自带的httpclient、 第三方库http 和 第三方库dio&...

概述:

app几乎都离不开与服务器的交互,本文主要讲解了flutter网络请求三种方式 flutter自带的httpclient、 第三方库http 和 第三方库dio  的简单实现 get 和 post请求,本文是笔者学习flutter网络模块知识总结,若有问题还望不腻赐教。

一.系统自带httpclient

1.使用中温馨提示

1.1.导入库

import 'dart:io'; // 网络请求
import 'dart:convert'; // 数据解析

1.2.uri的多种初始化方式

// 方法1
uri uri = uri(scheme: 'https', host: 'app.xxx.com', path: homenovicelisturl);
// 方法2
uri uri = uri.https('app.xxx.com', homenovicelisturl);
// uri方法3
uri uri = uri.parse(baseurl + homenovicelisturl);

2.简单使用

2.1.get请求

// 1.1 httpclient - get 

void loaddata_sys_get() async {
print('------loaddata_sys_get--------');

var httpclient = new httpclient();
var params = map<string, string>();

// uri方法1
uri uri =
 uri(scheme: 'https', host: 'app.xxx.com', path: homenovicelisturl);

// uri方法2
// uri uri = uri.https(
// 'app.xxx.com', homenovicelisturl);

// uri方法3
// uri uri = uri.parse(baseurl + homenovicelisturl);

var request = await httpclient.geturl(uri);

var headers = map<string, string>();
headers['loginsource'] = 'ios';
headers['useversion'] = '3.1.0';
headers['isencoded'] = '1';
headers['bundleid'] = 'com.xxx.xxx';

request.headers.add("loginsource", "ios");
request.headers.add("useversion", "3.1.0");
request.headers.add("isencoded", "1");
request.headers.add("bundleid", "com.xxx.xxx");

var response = await request.close();
var responsebody = await response.transform(utf8decoder()).join();

if (response.statuscode == httpstatus.ok) {
 print('请求头:${response.headers}');

 print('111请求成功代发数据为:\n $responsebody');
 print('--------------');
 map data = jsondecode(responsebody);
 print('222请求成功代发数据为:\n $data');
} else {
 print('\n\n\n11111==请求失败${response.statuscode}');
}
}

2.2.post请求

注意点:请求参数需要编码后放在request中

void loaddata_sys_post() async {
print('------loaddata_sys_post--------');

httpclient httpclient = new httpclient();

// queryparameters get请求的查询参数(适用于get请求???是吗???)
// uri uri = uri(
// scheme: "https", host: "app.xxx.com", path: homeregularlisturl);
// httpclientrequest request = await httpclient.posturl(uri);

var url = baseurl + homeregularlisturl;
httpclientrequest request = await httpclient.posturl(uri.parse(url));

// 设置请求头
request.headers.set("loginsource", "ios");
request.headers.set("useversion", "3.1.0");
request.headers.set("isencoded", "1");
request.headers.set("bundleid", "com.xxx.xxx");
// content-type大小写都ok
request.headers.set('content-type', 'application/json');

/// 添加请求体
/// https://*.com/questions/50278258/http-post-with-json-on-body-flutter-dart/50295533
map jsonmap = {'currentpage': '1'};
request.add(utf8.encode(json.encode(jsonmap)));

httpclientresponse response = await request.close();
string responsebody = await response.transform(utf8.decoder).join();
if (response.statuscode == httpstatus.ok) {
 print('请求成功');
 print(response.headers);
 print(responsebody);
}
}

二.请求第三方库 http

1.使用中温馨提示

1.1.添加依赖

dependencies:
 http: ^0.12.0 #latest version

1.2.导入库

import 'package:http/http.dart' as http; //导入前需要配置

2.简单使用

2.1. get请求

2.2.1. http - get1

 void loaddata_http_get() async {
 print('------loaddata_http_get--------');

 var client = http.client();

 var uri = uri.parse(baseurl + homenovicelisturl);

 http.response response = await client.get(uri);

 if (response.statuscode == httpstatus.ok) {
 print(response.body);
 } else {
 print('请求失败 code 码为${response.statuscode}');
 }
 }

2.2. http - get简便方法(链式编程)

void loaddata_http_get_convenience() async {
 print('------简便方法loaddata_http_get_convenience--------');

 var uri = uri.parse(baseurl + homenovicelisturl);

 http.client().get(uri).then((http.response response) {
 if (response.statuscode == httpstatus.ok) {
 print(response.body);
 } else {
 print('请求失败 code 码为${response.statuscode}');
 }
 });
 }

2.2. post请求

2.2.1.  http - post

 void loaddata_http_post() async {
 print('------ loaddata_http_post --------');

 var headers = map<string, string>();
 headers["loginsource"] = "ios";
 headers["useversion"] = "3.1.0";
 headers["isencoded"] = "1";
 headers["bundleid"] = "com.xxx.xxx";
 headers["loginsource"] = "ios";
 headers["content\-type"] = "application/json";

 map params = {'currentpage': '1'};
 // 嵌套两层都可以,但是具体哪个好还有待确认????
 var jsonparams = utf8.encode(json.encode(params));
 // var jsonparams = json.encode(params);

 var httpclient = http.client();

 var uri = uri.parse(baseurl + homenovicelisturl);

 http.response response =
 await httpclient.post(uri, body: jsonparams, headers: headers);

 if (response.statuscode == httpstatus.ok) {
 print(response.body);
 } else {
 print('请求失败 code 码���${response.statuscode}');
 }
 }

2.2.2. http - post简便方法(链式编程)

 void loaddata_http_post_convenience() async {
 print('------ loaddata_http_post --------');

 var headers = map<string, string>();
 headers["loginsource"] = "ios";
 headers["useversion"] = "3.1.0";
 headers["isencoded"] = "1";
 headers["bundleid"] = "com.xxx.xxx";
 headers["loginsource"] = "ios";
 headers["content\-type"] = "application/json";

 map params = {'currentpage': '1'};
 // 嵌套两层都可以,但是具体哪个好还有待确认????
 var jsonparams = utf8.encode(json.encode(params));
 // var jsonparams = json.encode(params);

 var httpclient = http.client();

 var url = baseurl + homeregularlisturl;

 httpclient.post(url, body: jsonparams, headers: headers).then((response) {
 print("response status: ${response.statuscode}");
 print("response body: ${response.body}");
 }).whencomplete(httpclient.close);
 }

三.请求第三方库 dio

1.使用中温馨提示

1.1.添加依赖

dependencies:
 dio: ^2.0.11 #latest version

1.2.导入库

import 'package:dio/dio.dart';

2.简单使用

2.1. get请求

注意:dio的get请求(baseurl都是在dio.option.baseurl设置的) 请求头可以在dio.option上设置,也可以在新建的option上设置,新建option是可选的

void loaddata_dio_get() async {
 var headers = map<string, string>();
 headers['loginsource'] = 'ios';
 headers['useversion'] = '3.1.0';
 headers['isencoded'] = '1';
 headers['bundleid'] = 'com.xxx.xxx';
 headers['content-type'] = 'application/json';

 dio dio = dio();
 dio.options.headers.addall(headers);
 dio.options.baseurl = baseurl;

 response response = await dio.get(homenovicelisturl);

 if (response.statuscode == httpstatus.ok) {
 print(response.headers);
 print(response.data);
 }
 }

2.2. post请求

注意:

dio.options.method设置是无效
dio dio = dio();
dio.options.method = 'post';

办法:
新建一个options对象,然后在发起请求的时候进行设置:
options option = options(method:'post');
response response = await dio.request(homeregularlisturl,data:{"currentpage": "1"}, options: option);

2.2.1. dio - 方式一(baseurl都是在dio.option.baseurl设置的)

注意:直接在 dio.options设置除methods以外的 请求头参数

void loaddata_dio_dioofoptionssetting() async {
 debugprint(
 ' \n post请求 ======================= 开始请求 =======================\n');
 var headers = map<string, string>();
 headers['loginsource'] = 'ios';
 headers['useversion'] = '3.1.0';
 headers['isencoded'] = '1';
 headers['bundleid'] = 'com.xxx.xxx';
 headers['content-type'] = 'application/json';

 dio dio = dio();
 dio.options.baseurl = baseurl;
 dio.options.connecttimeout = 60000;
 dio.options.receivetimeout = 60000;
 dio.options.headers.addall(headers);
 dio.options.method = 'post';

 options option = options(method: 'post');
 // response response = await dio.request(homeregularlisturl,
 // data: {"currentpage": "1"}, options: option);

 response response = await dio.post(homeregularlisturl,
 data: {"currentpage": "1"}, options: option);

 if (response.statuscode == httpstatus.ok) {
 debugprint('请求参数: ${response.request.queryparameters}');
 debugprint(
  '-------------------请求成功,请求结果如下:-----------------\n \n===请求求url: ${response.request.uri.tostring()} \n \n===请求 ���: \n${response.headers} \n \n===请求结果: \n${response.data}\n');
 debugprint('-------------------请求成功,请求结果打印完毕----------------');
 } else {
 print('请求失败');
 }
 }

2.2.2. dio - 方式二(baseurl都是在dio.option.baseurl设置的)

注意:在新建的option上设置请求头参数

void loaddata_dio_newoptionsetting() async {
 debugprint(' \n======================= 开始请求 =======================\n');
 var headers = map<string, string>();
 headers['loginsource'] = 'ios';
 headers['useversion'] = '3.1.0';
 headers['isencoded'] = '1';
 headers['bundleid'] = 'com.xxx.xxx';
 headers['content-type'] = 'application/json';

 options option = options(method: 'post');
 option.connecttimeout = 60000;
 option.receivetimeout = 60000;
 option.headers.addall(headers);

 dio dio = dio();
 dio.options.baseurl = baseurl;

 response response = await dio.post(homeregularlisturl,
 data: {"currentpage": 1}, options: option);
 // response response = await dio.request(homeregularlisturl,
 // data: {"currentpage": 1}, options: option);

 if (response.statuscode == httpstatus.ok) {
 debugprint('请求参数: ${response.request.queryparameters}');
 debugprint(
  '-------------------请求成功,请求结果如下:-----------------\n \n===请求url: ${response.request.uri.tostring()} \n \n===请求 头: \n${response.headers} \n \n===请求结果: \n${response.data}\n');
 debugprint('-------------------请求成功,请求结果打印完毕----------------');
 } else {
 print('请求失败');
 }
 }

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。