request method
isFullUrl
- url传入的是否为完整的一个URL,如果为true
,将忽略host
Implementation
@Doc(message: "向服务器发起http请求")
Future<dynamic> request(
{bool showErrorMsg = true,
String? loadingText,
String contentType = "",
Map<String, dynamic>? headers,
bool showDefaultLoading = true,
dynamic data,
ResponseType? responseType,
bool? nullParams,
RequestEncoder? requestEncoder,
DioStart? dioStart,bool? returnIsString,bool isFullUrl = false}) async {
try {
if (showDefaultLoading) {
showLoading(loadingText: loadingText);
}
final dio = getDio();
intrtceptors.add(ErrorInterceptor());
dio.interceptors.addAll(intrtceptors);
final contentTypeStr = contentType.isNotEmpty ? contentType : (httpMethod == HttpMethod.post ? io.ContentType.json.value : null);
final bodyParams = formData.files.isNotEmpty ? formData : (data ?? params);
dioStart?.call(dio,_host + url);
final queryParameters = httpMethod == HttpMethod.post ? null : (nullParams == true ? null : data ?? params);
final contentTypeString = httpMethod == HttpMethod.probuf ? kProtobufContentType : contentTypeStr;
final response = await dio.request(
isFullUrl ? url : (_host + url),
options: Options(
method: method,
contentType: contentTypeString,
headers: headers,
responseType: responseType,
requestEncoder: requestEncoder),
queryParameters: queryParameters,
data: bodyParams,
);
if (showDefaultLoading) {
closeLoading();
}
if (response.statusCode == 200) {
final data = response.data;
if(data is String){
if(returnIsString == true){
return data;
}
try{
return jsonDecode(data);
}catch(e){
throw AppException.appError(code: 10003,msg: "Unable to process server data");
}
}
return data;
}else{
throw AppException(code: response.statusCode ?? 10004, message: response.statusMessage??"ERROR");
}
} on DioError catch (e) {
if (showDefaultLoading) {
closeLoading();
}
throw e.error as AppException;
} catch (e) {
throw AppException.appError();
}
}