-
Notifications
You must be signed in to change notification settings - Fork 0
/
transfomer.dart
44 lines (38 loc) · 1.39 KB
/
transfomer.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import 'dart:async';
import 'package:dio/dio.dart';
/// If the request data is a `List` type, the [DefaultTransformer] will send data
/// by calling its `toString()` method. However, normally the List object is
/// not expected for request data( mostly need Map ). So we provide a custom
/// [Transformer] that will throw error when request data is a `List` type.
class MyTransformer extends DefaultTransformer {
@override
Future<String> transformRequest(RequestOptions options) async {
if (options.data is List<String>) {
throw new DioError(message: "Can't send List to sever directly");
} else {
return super.transformRequest(options);
}
}
/// The [Options] doesn't contain the cookie info. we add the cookie
/// info to [Options.extra], and you can retrieve it in [ResponseInterceptor]
/// and [Response] with `response.request.extra["cookies"]`.
@override
Future transformResponse(
RequestOptions options, ResponseBody response) async {
options.extra["self"] = 'XX';
return super.transformResponse(options, response);
}
}
main() async {
var dio = new Dio();
// Use custom Transformer
dio.transformer = new MyTransformer();
Response response = await dio.get("https://www.baidu.com");
print(response.request.extra["self"]);
try {
await dio.post("https://www.baidu.com", data: ["1", "2"]);
} catch (e) {
print(e);
}
print("xxx");
}