0
点赞
收藏
分享

微信扫一扫

Flutter中的http网络请求,30岁以后搞Android已经没有前途

一叶轻舟okok 2022-03-11 阅读 60
面试

responseData = responseData.replaceAll("{", “\n{”);
debugPrint(‘response.data=$responseData’);
}
} on DioError catch (e) {
print(“exception: $e”);
}

return;
}

关于代理设置代码块,在Dio 2.x版本和1.x版本上设置的方式是不同的,这是因为Dio 2.x版本代码重构的原因,1.x代码上onHttpClientCreate方法放在了Dio类中,而2.x版本将该方法封装到了一个名为DefaultHttpClientAdapter的类中,Dio类中的httpClientAdapter即是默认实现了DefaultHttpClientAdapter类的对象,所以此时根据httpClientAdapter对象来设置onHttpClientCreate为自定义方法即可。

1.x版本代理设置方法的代码块如下:

Dio dio = Dio();
dio.onHttpClientCreate = (HttpClient client) {
if(client == null) {
client = HttpClient();
}
client.findProxy = (url) {
return HttpClient.findProxyFromEnvironment(url, environment: {“http_proxy”: ‘http://192.168.124.94:8888’,});
};
return client;
};

拦截器

使用Dio处理网络请求可以设置拦截器,dio中定义了两个拦截器:LogInterceptor和CookieManager,这两个拦截器都是抽象类Interceptor的实现,具体是对抽象类中onRequest、onResponse、onError三个方法的实现,我们也可以自定义拦截器处理一些自己的需求。下面使用LogInterceptor来举例说明拦截器的作用:

//在上文dio使用的代码中加入如下代码,即添加了Log拦截器
dio.interceptors.add(LogInterceptor());

添加拦截器之后,执行请求,会看到控制台打印如下信息:

I/flutter (28939): *** Request ***
I/flutter (28939): uri: http://v.juhe.cn/weather/geo?format=2&key=939e592487c33b12c509f757500888b5&lon=116.39277&lat=39.933748
I/flutter (28939): method: GET
I/flutter (28939): contentType: application/json; charset=utf-8
I/flutter (28939): responseType: ResponseType.json
I/flutter (28939): followRedirects: true
I/flutter (28939): connectTimeout: 10000
I/flutter (28939): receiveTimeout: 10000
I/flutter (28939): extra: {}
I/flutter (28939): header:
I/flutter (28939):
I/flutter (28939): *** Response ***
I/flutter (28939): uri: http://v.juhe.cn/weather/geo?format=2&key=939e592487c33b12c509f757500888b5&lon=116.39277&lat=39.933748
I/flutter (28939): statusCode: 200
I/flutter (28939): headers:
I/flutter (28939): proxy-connection: Keep-alive
I/flutter (28939): etag: 063d270dc44003f39cf480b7ec6ff843
I/flutter (28939): content-type: application/json;charset=utf-8
I/flutter (28939): set-cookie: aliyungf_tc=AQAAAP85/D47jwIAsongemk2vUOG/ZUW; Path=/; HttpOnly
I/flutter (28939): transfer-encoding: chunked
I/flutter (28939): date: Sat, 02 Mar 2019 04:29:17 GMT
I/flutter (28939):
I/flutter (28939):

由打印结果可以看出LogInterceptor拦截器其实就是对request和response相关信息的打印,这有助于我们对http请求进行调试。

全局配置

由以上代码可以看出使用dio实现网络请求时,可以通过dio.options的进行全局通用配置,比如baseUrl、超时时间、请求的header信息等。

表单数据

使用post请求我们可以使用form表单的形式发送参数数据,代码如下:

Map<String, String> queryParameters = {‘format’: ‘2’, ‘key’: ‘939e592487c33b12c509f757500888b5’, ‘lon’: ‘116.39277’, ‘lat’: ‘39.933748’};
Response response = await dio.post("/weather/geo", data: FormData.from(queryParameters), options: Options());

通过抓取请求包,我们会发现content-type类型如下:

请求取消

比如跳转到某个页面请求了一条远程数据,但在数据没有回来之前关闭了该页面,那这条请求是可以在关闭页面时取消掉的,这要求你在发请求时使用cancelToken参数,如下:

CancelToken _cancelToken = CancelToken();
Map<String, String> queryParameters = {‘format’: ‘2’, ‘key’: ‘939e592487c33b12c509f757500888b5’, ‘lon’: ‘116.39277’, ‘lat’: ‘39.933748’};
Response response = await dio.post("/weather/geo", data: FormData.from(queryParameters), cancelToken: _cancelToken);

在页面退出之前可以通过调用_cancelToken.cancel()方法取消该请求。多个请求可以使用同一个CancelToken对象,故调用该对象的cancel()方法时所有的未完成的请求均会被取消。

文件下载

Dio中实现的文件下载功能也非常简单好用,实例代码如下:

Future getSavePath() async {
Directory externalStorageDir = await getExternalStorageDirectory();
String externalStoragePath = externalStorageDir.path + “/flutterdemo”;
Directory dir = Directory(externalStoragePath);
if(!dir.existsSync()) {
dir.createSync();
}
File file = File(dir.path + “/test.jpg”);
if(!file.existsSync()) {
file.createSync();
}
print(‘file.path = ${file.path}’);
return file.path;
}

Future _downloadImage() async {
Dio dio = Dio();
dio.options.baseUrl = “http://img.ipintu.cn/images/”;
dio.interceptors.add(LogInterceptor());
String savePath = await getSavePath();
try {
Response response = await dio.download(
“/baomanwayong_04.jpg”,
savePath,
onReceiveProgress: (int count, int total) {
if(total > 0) {
print((count / total * 100).toStringAsFixed(0) + “%”);
}
});
if (response.statusCode == 200) {
print(‘下载完成’);
}
} on DioError catch (e) {
print(“exception: $e”);
}

return;
}

点击按钮调用下载方法,控制台输出信息如下:

I/flutter ( 5603): file.path = /storage/emulated/0/flutterdemo/test.jpg
I/flutter ( 5603): *** Request ***
I/flutter ( 5603): uri: http://img.ipintu.cn/images/baomanwayong_04.jpg
I/flutter ( 5603): method: GET
I/flutter ( 5603): contentType: application/json; charset=utf-8
I/flutter ( 5603): responseType: ResponseType.stream
I/flutter ( 5603): followRedirects: true
I/flutter ( 5603): connectTimeout: 0
I/flutter ( 5603): receiveTimeout: 0
I/flutter ( 5603): extra: {}
I/flutter ( 5603): header:
I/flutter ( 5603):
I/flutter ( 5603): *** Response ***
I/flutter ( 5603): uri: http://img.ipintu.cn/images/baomanwayong_04.jpg
I/flutter ( 5603): statusCode: 200
I/flutter ( 5603): headers:
I/flutter ( 5603): last-modified: Fri, 11 May 2018 08:45:42 GMT
I/flutter ( 5603): date: Sat, 02 Mar 2019 07:17:01 GMT
I/flutter ( 5603): x-reqid: BwAAABaE5ayYe4YV
I/flutter ( 5603): access-control-expose-headers: X-Log, X-Reqid
I/flutter ( 5603): x-m-reqid: mmcAAMu4tv7GEogV
I/flutter ( 5603): server: marco/2.8
I/flutter ( 5603): x-request-id: 8836d6cebf799bbe22c678f2c9cdb5d3; 6b3ff4ec13b9de472e4bae298d38d9c9
I/flutter ( 5603): x-log: redis.g/404;mc.g/404;redis.g;rs40_shard.sel:4/not found;rdb.g;bs.r.48.179.10783842506;DBD;v4.get;rwro.get:5;RS.dbs:5;RS:6;redis.s;redis.g;IO:42
I/flutter ( 5603): content-disposition: inline; filename=“baomanwayong_04.jpg”; filename*=utf-8’ 'baomanwayong_04.jpg
I/flutter ( 5603): accept-ranges: bytes
I/flutter ( 5603): content-length: 151887
I/flutter ( 5603): etag: “Fnlr7Ngb3uIdCjft615r4IJd6-BU”
I/flutter ( 5603): x-qiniu-zone: 0
I/flutter ( 5603): connection: keep-alive
I/flutter ( 5603): cache-control: max-age=2592000
I/flutter ( 5603): access-control-allow-origin: *
I/flutter ( 5603): age: 304
I/flutter ( 5603): content-type: image/jpeg

尾声

最后,我再重复一次,如果你想成为一个优秀的 Android 开发人员,请集中精力,对基础和重要的事情做深度研究。

对于很多初中级Android工程师而言,想要提升技能,往往是自己摸索成长,不成体系的学习效果低效漫长且无助。 整理的这些架构技术希望对Android开发的朋友们有所参考以及少走弯路,本文的重点是你有没有收获与成长,其余的都不重要,希望读者们能谨记这一点。

这里,笔者分享一份从架构哲学的层面来剖析的视频及资料分享给大家梳理了多年的架构经验,筹备近6个月最新录制的,相信这份视频能给你带来不一样的启发、收获。

Android进阶学习资料库

一共十个专题,包括了Android进阶所有学习资料,Android进阶视频,Flutter,java基础,kotlin,NDK模块,计算机网络,数据结构与算法,微信小程序,面试题解析,framework源码!

  • 自行下载直达领取链接:点击这里前往GitHub

4/Android-P7/blob/master/Android%E5%BC%80%E5%8F%91%E4%B8%8D%E4%BC%9A%E8%BF%99%E4%BA%9B%EF%BC%9F%E5%A6%82%E4%BD%95%E9%9D%A2%E8%AF%95%E6%8B%BF%E9%AB%98%E8%96%AA%EF%BC%81.md)

举报

相关推荐

0 条评论