Skip to content

Commit

Permalink
update to 2.1.8
Browse files Browse the repository at this point in the history
  • Loading branch information
wendux committed Jul 2, 2019
1 parent 623fef3 commit 3b2f765
Show file tree
Hide file tree
Showing 10 changed files with 103 additions and 62 deletions.
53 changes: 39 additions & 14 deletions example/test.dart
Original file line number Diff line number Diff line change
@@ -1,21 +1,46 @@
import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';

main() async {
var formData = new FormData.from({
"param1": "-1",
"param2": "-1",
"param3": "-1",
"param4": "-1",
"param5": null,
"param8": {"a": "b", "b": "c"},
"music": new UploadFileInfo(new File("./example/bee.mp4"), "be.mp4"),
});
// var formData = new FormData.from({
// "param1": "-1",
// "param1": "-1",
// "param2": "-1",
// "param3": "-1",
// "param4": "-1",
// "param5": null,
// "param8": {"a": "b", "b": "c"},
// "dd":["X",4]
// //"music": new UploadFileInfo(new File("./example/bee.mp4"), "be.mp4"),
// });
//
// //print(formData);
//
// var t = await formData.asBytesAsync();
// print("formStreamSize = ${t.length}");
// print("formData.length = ${formData.length}");
// print("asBytes.length = ${formData.asBytes().length}");
// print(utf8.decode(t)==formData.toString());

var t = await formData.asBytesAsync();
print("formStreamSize = ${t.length}");
print("formData.length = ${formData.length}");
print(formData.length == t.length);
//print(formData);
Response response;
//upload a video
// response = await Dio().post(
// "http://localhost:3000/upload",
// data: FormData.from({
// "test":"haha",
// "file": UploadFileInfo(File("./example/bee.mp4"), "bee.mp4"),
// "file2": UploadFileInfo(File("./example/upload.txt"), "xx.text"),
// "x":[5,"f"]
// }),
// onSendProgress: (received, total) {
// if (total != -1) {
// print((received / total * 100).toStringAsFixed(0) + "%");
// }
// },
// );

response = await Dio().get("https://google.com", options: Options(connectTimeout:1000));
print(response);

}
4 changes: 4 additions & 0 deletions package_src/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# 2.1.8

- fix #354 #312
- Allow "delete" method with request body(#223)

# 2.1.7

Expand Down
47 changes: 35 additions & 12 deletions package_src/lib/src/adapter.dart
Original file line number Diff line number Diff line change
Expand Up @@ -98,23 +98,23 @@ class ResponseBody {

/// The default HttpClientAdapter for Dio is [DefaultHttpClientAdapter].
class DefaultHttpClientAdapter extends HttpClientAdapter {
HttpClient _httpClient;

Future<ResponseBody> fetch(
RequestOptions options,
Stream<List<int>> requestStream,
Future cancelFuture,
) async {
_configHttpClient();
var _httpClient = _configHttpClient(cancelFuture);

Future requestFuture;
if (options.connectTimeout > 0) {
// Because there is a bug in [httpClient.connectionTimeout] now, we replace it
// with `Future.timeout()` when it comes.
// Bug issue: https://github.com/dart-lang/sdk/issues/34980.
//_httpClient.connectionTimeout= Duration(milliseconds: options.connectTimeout);
requestFuture = _httpClient
.openUrl(options.method, options.uri)
.timeout(Duration(milliseconds: options.connectTimeout));
// _httpClient.connectionTimeout =
// Duration(milliseconds: options.connectTimeout);
requestFuture = _httpClient.openUrl(options.method, options.uri)
.timeout(Duration(milliseconds: options.connectTimeout));
} else {
_httpClient.connectionTimeout = null;
requestFuture = _httpClient.openUrl(options.method, options.uri);
Expand Down Expand Up @@ -164,17 +164,40 @@ class DefaultHttpClientAdapter extends HttpClientAdapter {
);
}

void _configHttpClient() {
if (_httpClient == null) _httpClient = new HttpClient();
_httpClient.idleTimeout = Duration(seconds: 3);
if (onHttpClientCreate != null) {
//user can return a new HttpClient instance
_httpClient = onHttpClientCreate(_httpClient) ?? _httpClient;
HttpClient _configHttpClient(Future cancelFuture) {
if (cancelFuture != null) {
var _httpClient = HttpClient();
if (onHttpClientCreate != null) {
//user can return a new HttpClient instance
_httpClient = onHttpClientCreate(_httpClient) ?? _httpClient;
}
_httpClient.idleTimeout = Duration(seconds: 0);
cancelFuture.whenComplete(() {
Future.delayed(Duration(seconds: 0)).then((e) {
try {
_httpClient.close(force: true);
} catch (e) {
//...
}
});
});
return _httpClient;
} else if (_defaultHttpClient == null) {
_defaultHttpClient = HttpClient();
_defaultHttpClient.idleTimeout = Duration(seconds: 3);
if (onHttpClientCreate != null) {
//user can return a new HttpClient instance
_defaultHttpClient =
onHttpClientCreate(_defaultHttpClient) ?? _defaultHttpClient;
}
}
return _defaultHttpClient;
}

/// [Dio] will create new HttpClient when it is needed.
/// If [onHttpClientCreate] is provided, [Dio] will call
/// it when a new HttpClient created.
OnHttpClientCreate onHttpClientCreate;

HttpClient _defaultHttpClient;
}
6 changes: 3 additions & 3 deletions package_src/lib/src/dio.dart
Original file line number Diff line number Diff line change
Expand Up @@ -609,7 +609,7 @@ class Dio {
queryParameters: queryParameters,
cancelToken: cancelToken,
options: options,
onSendProgress: onSendProgress ?? onSendProgress,
onSendProgress: onSendProgress,
onReceiveProgress: onReceiveProgress,
);
}
Expand All @@ -632,7 +632,7 @@ class Dio {
data: data,
cancelToken: cancelToken,
options: options,
onSendProgress: onSendProgress ?? onSendProgress,
onSendProgress: onSendProgress ,
onReceiveProgress: onReceiveProgress,
);
}
Expand Down Expand Up @@ -822,7 +822,7 @@ class Dio {
var data = options.data;
List<int> bytes;
Stream<List<int>> stream;
if (data != null && ["POST", "PUT", "PATCH"].contains(options.method)) {
if (data != null && ["POST", "PUT", "PATCH", "DELETE"].contains(options.method)) {
// Handle the FormData
int length;
if (data is Stream) {
Expand Down
24 changes: 4 additions & 20 deletions package_src/lib/src/form_data.dart
Original file line number Diff line number Diff line change
Expand Up @@ -86,24 +86,6 @@ class FormData extends MapMixin<String, dynamic> {
return _fileFieldLen;
}

// void writeMapLength(buf, key, value, len) {
//
// value.keys.toList().forEach((mapKey) {
// var nestedKey = '${key}[${mapKey}]';
// len += _textFieldLength;
// buf.write("$nestedKey${value[mapKey]}");
// if (value[mapKey] is Map) {
// writeMapLength(buf, nestedKey, value[mapKey], len);
// }else if (value[mapKey] is UploadFileInfo){
// var e = value[mapKey];
// len += _fileFieldLength;
// _fileInfo(nestedKey, value[mapKey]);
// len += e.bytes?.length ?? e.file.lengthSync();
// len += utf8.encode('\r\n').length;
// }
// print(buf);
// });
// }

/// Get the length of the formData (as bytes)
int get length {
Expand Down Expand Up @@ -197,7 +179,7 @@ class FormData extends MapMixin<String, dynamic> {
});
} else {
len += _textFieldLength;
buf.write("$key$e");
buf.write("$key[]$e");
}
});
}
Expand Down Expand Up @@ -243,8 +225,10 @@ class FormData extends MapMixin<String, dynamic> {
bytes.addAll(_chunkHeader(data, key, e));
bytes.addAll(e.bytes ?? e.file.readAsBytesSync());
bytes.addAll(utf8.encode('\r\n'));
} else if(e is Map){
handleMapField(bytes, key, e);
} else {
bytes.addAll(_textField(data, key, e));
bytes.addAll(_textField(data, key+"[]", e));
}
});
}
Expand Down
6 changes: 3 additions & 3 deletions package_src/lib/src/interceptor.dart
Original file line number Diff line number Diff line change
Expand Up @@ -69,21 +69,21 @@ class Interceptor {
/// If you want to reject the request with a error message,
/// you can return a [DioError] object or return [dio.reject] .
/// If you want to continue the request, return the [Options] object.
onRequest(RequestOptions options) => options;
FutureOr<dynamic> onRequest(RequestOptions options) => options;

/// The callback will be executed on success.
///
/// If you want to reject the request with a error message,
/// you can return a [DioError] object or return [dio.reject] .
/// If you want to continue the request, return the [Response] object.
onResponse(Response response) => response;
FutureOr<dynamic> onResponse(Response response) => response;

/// The callback will be executed on error.
///
/// If you want to resolve the request with some custom data,
/// you can return a [Response] object or return [dio.resolve].
/// If you want to continue the request, return the [DioError] object.
onError(DioError err) => err;
FutureOr<dynamic> onError(DioError err) => err;
}

class InterceptorsWrapper extends Interceptor {
Expand Down
7 changes: 4 additions & 3 deletions package_src/lib/src/interceptors/cookie_mgr.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import 'dart:async';
import 'dart:io';
import '../interceptor.dart';
import '../options.dart';
Expand Down Expand Up @@ -29,7 +30,7 @@ class CookieManager extends Interceptor {
}

@override
onRequest(RequestOptions options) {
FutureOr<dynamic> onRequest(RequestOptions options) {
var cookies = cookieJar.loadForRequest(options.uri);
cookies.removeWhere((cookie) =>
cookie.value == invalidCookieValue &&
Expand All @@ -40,10 +41,10 @@ class CookieManager extends Interceptor {
}

@override
onResponse(Response response) => _saveCookies(response);
FutureOr<dynamic> onResponse(Response response) => _saveCookies(response);

@override
onError(DioError err) => _saveCookies(err.response);
FutureOr<dynamic> onError(DioError err) => _saveCookies(err.response);

_saveCookies(Response response) {
if (response != null && response.headers != null) {
Expand Down
11 changes: 6 additions & 5 deletions package_src/lib/src/interceptors/log.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'dart:async';

import '../interceptor.dart';
import '../options.dart';
import '../response.dart';
Expand Down Expand Up @@ -37,7 +39,7 @@ class LogInterceptor extends Interceptor {
final logSize;

@override
onRequest(RequestOptions options) {
FutureOr<dynamic> onRequest(RequestOptions options) {
print('*** Request ***');
printKV('uri', options.uri);

Expand All @@ -64,7 +66,7 @@ class LogInterceptor extends Interceptor {
}

@override
onError(DioError err) {
FutureOr<dynamic> onError(DioError err) {
if (error) {
print('*** DioError ***:');
print(err);
Expand All @@ -75,7 +77,7 @@ class LogInterceptor extends Interceptor {
}

@override
onResponse(Response response) {
FutureOr<dynamic> onResponse(Response response) {
print("*** Response ***");
_printResponse(response);
}
Expand All @@ -84,8 +86,7 @@ class LogInterceptor extends Interceptor {
printKV('uri', response?.request?.uri);
if (responseHeader) {
printKV('statusCode', response.statusCode);
if(response.isRedirect)
printKV('redirect',response.realUri);
if (response.isRedirect) printKV('redirect', response.realUri);
print("headers:");
print(" " + response?.headers?.toString()?.replaceAll("\n", "\n "));
}
Expand Down
2 changes: 1 addition & 1 deletion package_src/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -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.1.7
version: 2.1.8
homepage: https://github.com/flutterchina/dio
author: wendux <[email protected]>

Expand Down
5 changes: 4 additions & 1 deletion package_src/test/dio_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,10 @@ void main() {
FormData formData = FormData.from({
"name": "wendux",
"age": 25,
"other": {"a": 1, "b": 2}
"other": {"a": 1, "b": 2},
"test":["xx",2]
});

formData.remove("name");
formData["xx"] = 9;
formData.add(
Expand All @@ -120,6 +122,7 @@ void main() {
);
var t = await formData.asBytesAsync();
expect(formData.length, t.length);
expect(formData.length, formData.asBytes().length);
await dio.post("/test", data: formData);
formData.clear();
expect(formData.length, 0);
Expand Down

0 comments on commit 3b2f765

Please sign in to comment.