import 'dart:convert';
import 'package:dio/dio.dart';
Dio dio = new Dio();
class HttpUtils {
HttpUtils() {
dio.interceptors.add(CustomInterceptors());
}
Future get(path, query) async {
Response resp;
try {
resp = await dio.get(path, queryParameters: query);
if (resp.statusCode == 200) {
String val = resp.toString();
return jsonDecode(val);
} else {
String val = resp.toString();
return jsonDecode(val);
}
} catch (error) {
return error;
}
}
Future post(path, data) async {
Response resp;
try {
resp = await dio.post(path, data: data);
if (resp.statusCode == 200) {
String val = resp.toString();
return jsonDecode(val);
} else {
String val = resp.toString();
return jsonDecode(val);
}
} catch (error) {
return error;
}
}
Future put(path, data) async {
Response resp;
try {
resp = await dio.put(path, data: data);
if (resp.statusCode == 200) {
String val = resp.toString();
return jsonDecode(val);
} else {
String val = resp.toString();
return jsonDecode(val);
}
} catch (error) {
return error;
}
}
}
class CustomInterceptors extends InterceptorsWrapper {
@override
Future onRequest(RequestOptions options) {
options.connectTimeout = 30000;
options.receiveTimeout = 30000;
options.headers["Authorization"] = "Bearer ";
options.headers['content-type'] = "application/x-www-form-urlencoded";
print('------------------------請求開始------------------------');
print('- 請求方式:${options?.method}');
print('- 請求資料: ${options?.data}');
print('- 請求頭資訊:${options.headers}');
return super.onRequest(options);
}
@override
Future onResponse(Response response) {
print('------------------------請求結束------------------------');
return super.onResponse(response);
}
@override
Future onError(DioError err) {
print('------------------------請求出錯------------------------');
print('- 錯誤型別:${err.type}');
print('- 錯誤資訊:${err.message}');
print('- error: $err');
return super.onError(err);
}
}
複製程式碼