request method
Executes an HTTP request.
This is the core method that performs the actual HTTP request using the underlying HTTP client library.
Parameters:
- request: The request configuration containing URL, method, headers, body, etc.
Returns a Future that completes with an AdapterResponse containing the response data, status code, headers, etc.
Throws AdapterException if the request fails due to timeout, network error, or other issues.
Example:
final request = AdapterRequest(
baseUrl: 'https://api.example.com',
path: '/users/123',
method: HttpMethod.get,
);
final response = await adapter.request(request);
print('Status: ${response.statusCode}');
print('Data: ${response.data}');
Implementation
@override
Future<AdapterResponse> request(AdapterRequest request) async {
try {
// 先执行请求拦截器
final interceptedRequest = await _executeRequestInterceptors(request);
// 转换 AdapterRequest 到 Dio RequestOptions
final options = _convertToOptions(interceptedRequest);
// 构建请求体
final requestBody = _buildRequestBody(interceptedRequest);
// 转换 CancelToken
final dioCancelToken = _convertCancelToken(interceptedRequest.cancelToken);
// 处理 RESTful 参数
String path = interceptedRequest.path;
interceptedRequest.pathParams.forEach((key, value) {
path = path.replaceAll('{$key}', value.toString());
});
// 直接使用 path,Dio 会自动处理:
// - 如果 path 是完整 URL (http:// 或 https://),Dio 直接使用
// - 如果 path 是相对路径,Dio 会拼接 dio.options.baseUrl
final response = await _dio.request(
path,
data: requestBody,
queryParameters: interceptedRequest.queryParams,
options: options,
cancelToken: dioCancelToken,
);
// 转换 Dio Response 到 AdapterResponse
var adapterResponse = _convertFromResponse(response, interceptedRequest);
// 执行响应拦截器
adapterResponse = await _executeResponseInterceptors(adapterResponse);
return adapterResponse;
} on _EarlyResponseException catch (e) {
// 拦截器提前返回了响应
return e.response;
} on DioException catch (e) {
// 执行错误拦截器
var exception = _convertException(e);
exception = await _executeErrorInterceptors(exception);
throw exception;
} catch (e) {
// 其他错误也通过错误拦截器
var exception = AdapterException(
message: e.toString(),
type: AdapterExceptionType.unknown,
originalError: e,
);
exception = await _executeErrorInterceptors(exception);
throw exception;
}
}