Skip to content
Permalink
Browse files

fix #161

  • Loading branch information...
duwen
duwen committed Feb 15, 2019
1 parent f83d92b commit deb3388c525f4eae83458c6579c5ff9423e50133
Showing with 112 additions and 82 deletions.
  1. +1 −1 README-ZH.md
  2. +1 −1 README.md
  3. +29 −40 example/cancel_request.dart
  4. +33 −15 example/dio.dart
  5. +2 −1 example/download.dart
  6. +0 −1 example/test.dart
  7. +31 −8 lib/src/dio.dart
  8. +11 −11 lib/src/interceptors/log.dart
  9. +3 −3 lib/src/options.dart
  10. +1 −1 pubspec.yaml
@@ -60,7 +60,7 @@ Dio dio = new Dio();
response = await dio.get("/test?id=12&name=wendu")
print(response.data.toString());
// 请求参数也可以通过对象传递,上面的代码等同于:
response = await dio.get("/test", queryParameters: {"id": '12', "name": "wendu"});
response = await dio.get("/test", queryParameters: {"id": 12, "name": "wendu"});
print(response.data.toString());
```

@@ -75,7 +75,7 @@ Dio dio = new Dio();
response = await dio.get("/test?id=12&name=wendu")
print(response.data.toString());
// Optionally the request above could also be done as
response = await dio.get("/test", queryParameters: {"id": '12', "name": "wendu"});
response = await dio.get("/test", queryParameters: {"id": 12, "name": "wendu"});
print(response.data.toString());
```

@@ -6,52 +6,41 @@ main() async {
// Token can be shared with different requests.
CancelToken token = new CancelToken();
// In one minute, we cancel!
new Timer(new Duration(milliseconds: 1000), () {
new Timer(new Duration(milliseconds: 200), () {
token.cancel("cancelled");
});

// The follow three requests with the same token.
var url1 = "https://accounts.google.com";
// var url2 = "https://www.facebook.com";
// var url3 = "https://www.baidu.com";
Response response;
try {
response = await dio.get(url1, cancelToken: token);
print(response);
} catch (e) {
var url2 = "https://www.facebook.com";
var url3 = "https://www.baidu.com";

dio
.get(url1, cancelToken: token)
.then((response) => print('${response.request.path}: succeed!'))
.catchError(
(e) {
if (CancelToken.isCancel(e)) {
print('$url1: $e');
}
},
);

dio
.get(url2, cancelToken: token)
.then((response) => print('${response.request.path}: succeed!'))
.catchError((e) {
if (CancelToken.isCancel(e)) {
print('$url1: $e');
print('$url2: $e');
}
}

/**
* 由于dart-lang #34586 bug所致,下面链式调用方式会抛出异常,目前的解决方法是使用await和try/catch
* 的方式来调用。
* 相关issue:
* https://github.com/dart-lang/sdk/issues/35426
* https://github.com/dart-lang/sdk/issues/34586
**/
// dio.get(url1, cancelToken: token)
// .then((response) => print('${response.request.path}: succeed!'))
// .catchError((DioError e) {
// if (CancelToken.isCancel(e)) {
// print('$url1: $e');
// }
// });
});

// dio.get(url2, cancelToken: token)
// .then((response) => print('${response.request.path}: succeed!'))
// .catchError((DioError e) {
// if (CancelToken.isCancel(e)) {
// print('$url2: $e');
// }
// });
//
// dio.get(url3, cancelToken: token)
// .then((response) => print('${response.request.path}: succeed!'))
// .catchError((DioError e) {
// if (CancelToken.isCancel(e)) {
// print('$url3: $e');
// }
// });
dio
.get(url3, cancelToken: token)
.then((response) => print('${response.request.path}: succeed!'))
.catchError((e) {
if (CancelToken.isCancel(e)) {
print('$url3: $e');
}
});
}
@@ -2,33 +2,50 @@ import 'dart:io';
import 'package:dio/dio.dart';

main() async {
var dio = new Dio();
var dio = Dio();
dio.options.baseUrl = "http://www.dtworkroom.com/doris/1/2.0.0/";
dio.options.connectTimeout = 5000; //5s
dio.options.receiveTimeout = 5000;
dio.options.headers = {'user-agent': 'dio', 'common-header': 'xx'};
dio.interceptors.add(LogInterceptor(responseBody: false)); //Open log

dio.interceptors.add(InterceptorsWrapper(onRequest: (Options options) {
// return ds.resolve(new Response(data:"xxx"));
// return ds.reject(new DioError(message: "eh"));
return options;
}));
// Or you can create dio instance and config it as follow:
// var dio = Dio(BaseOptions(
// baseUrl: "http://www.dtworkroom.com/doris/1/2.0.0/",
// connectTimeout: 5000,
// receiveTimeout: 5000,
// headers: {'user-agent': 'dio', 'common-header': 'xx'},
// ));

dio.interceptors
..add(InterceptorsWrapper(
onRequest: (Options options) {
// return ds.resolve( Response(data:"xxx"));
// return ds.reject( DioError(message: "eh"));
return options;
},
))
..add(LogInterceptor(responseBody: false)); //Open log;

Response response = await dio.get("https://www.google.com/");
print(response.data);

// Download a file
response = await dio.download("https://www.google.com/", "./xx.html",
onReceiveProgress: (received, total) {
print('$received,$total');
});
response = await dio.download(
"https://www.google.com/",
"./example/xx.html",
queryParameters: {"a": 1},
onReceiveProgress: (received, total) {
if (total != -1) {
print('$received,$total');
}
},
);

// Create a FormData
FormData formData = new FormData.from({
FormData formData = FormData.from({
"name": "wendux",
"age": 25,
"file": new UploadFileInfo(new File("./example/upload.txt"), "upload.txt")
"file": UploadFileInfo(File("./example/upload.txt"), "upload.txt")
});

// Send FormData
@@ -42,8 +59,9 @@ main() async {
"info": {"name": "wendux", "age": 25}
},
// Send data with "application/x-www-form-urlencoded" format
options: new Options(
contentType: ContentType.parse("application/x-www-form-urlencoded")),
options: Options(
contentType: ContentType.parse("application/x-www-form-urlencoded"),
),
);
print(response.data);
}
@@ -13,7 +13,8 @@ main() async {
// This is big file(about 200M)
// var url = "http://download.dcloud.net.cn/HBuilder.9.0.2.macosx_64.dmg";

var url = "https://cdn.jsdelivr.net/gh/flutterchina/flutter-in-action@1.0/docs/imgs/book.jpg";
var url =
"https://cdn.jsdelivr.net/gh/flutterchina/flutter-in-action@1.0/docs/imgs/book.jpg";
await download1(dio, url, "./example/book1.jpg");
await download2(dio, url, "./example/book2.jpg");
}
@@ -1,5 +1,4 @@
import 'dart:io';

import 'package:dio/dio.dart';

main() async {
@@ -26,6 +26,28 @@ typedef ProgressCallback = void Function(int count, int total);
/// A powerful Http client for Dart, which supports Interceptors,
/// Global configuration, FormData, File downloading etc. and Dio is
/// very easy to use.
///
/// You can create a dio instance and config it by two ways:
/// 1. create first , then config it
///
/// ```dart
/// var dio = Dio();
/// dio.options.baseUrl = "http://www.dtworkroom.com/doris/1/2.0.0/";
/// dio.options.connectTimeout = 5000; //5s
/// dio.options.receiveTimeout = 5000;
/// dio.options.headers = {'user-agent': 'dio', 'common-header': 'xx'};
/// ```
/// 2. create and config it:
///
/// ```dart
/// var dio = Dio(BaseOptions(
/// baseUrl: "http://www.dtworkroom.com/doris/1/2.0.0/",
/// connectTimeout: 5000,
/// receiveTimeout: 5000,
/// headers: {'user-agent': 'dio', 'common-header': 'xx'},
/// ));
/// ```

class Dio {
/// Create Dio instance with default [Options].
/// It's mostly just one Dio instance in your application.
@@ -66,7 +88,7 @@ class Dio {
/// Handy method to make http GET request, which is a alias of [Dio.request].
Future<Response<T>> get<T>(
String path, {
Map<String, dynamic /*String|Iterable<String>*/ > queryParameters,
Map<String, dynamic> queryParameters,
Options options,
CancelToken cancelToken,
ProgressCallback onReceiveProgress,
@@ -99,7 +121,7 @@ class Dio {
Future<Response<T>> post<T>(
String path, {
data,
Map<String, dynamic /*String|Iterable<String>*/ > queryParameters,
Map<String, dynamic> queryParameters,
Options options,
CancelToken cancelToken,
ProgressCallback onSendProgress,
@@ -139,7 +161,7 @@ class Dio {
Future<Response<T>> put<T>(
String path, {
data,
Map<String, dynamic /*String|Iterable<String>*/ > queryParameters,
Map<String, dynamic> queryParameters,
Options options,
CancelToken cancelToken,
ProgressCallback onSendProgress,
@@ -179,7 +201,7 @@ class Dio {
Future<Response<T>> head<T>(
String path, {
data,
Map<String, dynamic /*String|Iterable<String>*/ > queryParameters,
Map<String, dynamic> queryParameters,
Options options,
CancelToken cancelToken,
}) {
@@ -211,7 +233,7 @@ class Dio {
Future<Response<T>> delete<T>(
String path, {
data,
Map<String, dynamic /*String|Iterable<String>*/ > queryParameters,
Map<String, dynamic> queryParameters,
Options options,
CancelToken cancelToken,
}) {
@@ -243,7 +265,7 @@ class Dio {
Future<Response<T>> patch<T>(
String path, {
data,
Map<String, dynamic /*String|Iterable<String>*/ > queryParameters,
Map<String, dynamic> queryParameters,
Options options,
CancelToken cancelToken,
ProgressCallback onSendProgress,
@@ -364,7 +386,7 @@ class Dio {
String urlPath,
savePath, {
ProgressCallback onReceiveProgress,
Map<String, dynamic /*String|Iterable<String>*/ > queryParameters,
Map<String, dynamic> queryParameters,
CancelToken cancelToken,
lengthHeader = HttpHeaders.contentLengthHeader,
data,
@@ -460,6 +482,7 @@ class Dio {
await file.delete();
}
}

subscription = stream.listen(
(data) {
subscription.pause();
@@ -560,7 +583,7 @@ class Dio {
Future<Response<T>> request<T>(
String path, {
data,
Map<String, dynamic /*String|Iterable<String>*/ > queryParameters,
Map<String, dynamic> queryParameters,
CancelToken cancelToken,
Options options,
ProgressCallback onSendProgress,
@@ -5,6 +5,16 @@ import '../dio_error.dart';
import 'dart:math' as math;

class LogInterceptor extends Interceptor {
LogInterceptor({
this.request = true,
this.requestHeader = true,
this.requestBody = false,
this.responseHeader = true,
this.responseBody = false,
this.error = true,
this.logSize = 2048,
});

/// Print request [Options]
bool request;

@@ -26,16 +36,6 @@ class LogInterceptor extends Interceptor {
/// Log size per print
final logSize;

LogInterceptor({
this.request = true,
this.requestHeader = true,
this.requestBody = false,
this.responseHeader = true,
this.responseBody = false,
this.error = true,
this.logSize = 2048,
});

@override
onRequest(RequestOptions options) {
print('*** Request ***');
@@ -85,7 +85,7 @@ class LogInterceptor extends Interceptor {
print(" " + response.headers.toString().replaceAll("\n", "\n "));
}
if (responseBody) {
print("data:");
print("Response Text:");
printAll(response.toString());
}
print("");
@@ -1,6 +1,7 @@
import 'dart:io';
import 'dio.dart';
import 'cancel_token.dart';
import 'transformer.dart';

/// ResponseType indicates which transformation should
/// be automatically applied to the response data by Dio.
@@ -197,10 +198,9 @@ class RequestOptions extends Options {
List<String> s = _url.split(":/");
_url = s[0] + ':/' + s[1].replaceAll("//", "/");
}
String query = Uri(queryParameters: queryParameters).query;
String query = Transformer.urlEncodeMap(queryParameters);
if (query.isNotEmpty) {
_url += (_url.contains("?") ? "&" : "?") +
Uri(queryParameters: queryParameters).query;
_url += (_url.contains("?") ? "&" : "?") + query;
}
// Normalize the url.
return Uri.parse(_url).normalizePath();
@@ -1,6 +1,6 @@
name: dio
description: A powerful Http client for Dart, which supports Interceptors, FormData, Request Cancellation, File Downloading, Timeout etc.
version: 2.0.4
version: 2.0.5
homepage: https://github.com/flutterchina/dio
author: wendux <824783146@qq.com>

0 comments on commit deb3388

Please sign in to comment.
You can’t perform that action at this time.