投稿功能

This commit is contained in:
Developer
2026-03-30 07:32:12 +08:00
parent 59d82c9029
commit aeddc200a7
6 changed files with 986 additions and 30 deletions

View File

@@ -49,7 +49,7 @@ class HttpClient {
);
}
/// POST请求
/// POST请求 - JSON格式
static Future<HttpResponse> post(
String path, {
Map<String, dynamic>? data,
@@ -65,7 +65,23 @@ class HttpClient {
);
}
/// 通用请求方法
/// POST请求 - FormData格式
static Future<HttpResponse> postForm(
String path, {
Map<String, dynamic>? data,
Map<String, String>? headers,
Duration? timeout,
}) async {
return _requestForm(
'POST',
path,
data: data,
headers: headers,
timeout: timeout,
);
}
/// 通用请求方法 - JSON格式
static Future<HttpResponse> _request(
String method,
String path, {
@@ -147,6 +163,90 @@ class HttpClient {
throw HttpException('请求失败:$e');
}
}
/// FormData格式请求方法
static Future<HttpResponse> _requestForm(
String method,
String path, {
Map<String, dynamic>? queryParameters,
Map<String, dynamic>? data,
Map<String, String>? headers,
Duration? timeout,
}) async {
try {
final url = '$_baseUrl$path';
_debugLog('FormData请求 $method $url');
if (queryParameters != null) {
_debugLog('查询参数: $queryParameters');
}
if (data != null) {
_debugLog('表单数据: $data');
}
final formData = FormData.fromMap(data ?? {});
final options = Options(
method: method,
headers: headers != null
? {..._options.headers!, ...headers}
: _options.headers,
);
options.headers?['Content-Type'] = 'multipart/form-data';
if (timeout != null) {
options.connectTimeout = timeout;
options.receiveTimeout = timeout;
options.sendTimeout = timeout;
}
Response response;
if (method.toUpperCase() == 'POST') {
response = await _dio.post(
url,
data: formData,
queryParameters: queryParameters,
options: options,
);
} else {
throw UnsupportedError('FormData only supports POST method');
}
_debugLog('响应状态: ${response.statusCode}');
_debugLog('响应数据: ${response.data}');
return HttpResponse(
statusCode: response.statusCode ?? 0,
body: response.data is String
? response.data
: json.encode(response.data),
headers: response.headers.map.cast<String, String>(),
);
} on DioException catch (e) {
_debugLog('Dio异常: ${e.type} - ${e.message}');
String message;
switch (e.type) {
case DioExceptionType.connectionTimeout:
case DioExceptionType.sendTimeout:
case DioExceptionType.receiveTimeout:
message = '请求超时,请检查网络连接';
break;
case DioExceptionType.connectionError:
message = '网络连接失败,请检查网络设置';
break;
case DioExceptionType.badResponse:
message = '服务器错误: ${e.response?.statusCode} - ${e.response?.data}';
break;
default:
message = '请求失败: ${e.message}';
}
throw HttpException(message);
} catch (e) {
_debugLog('未知异常: $e');
throw HttpException('请求失败:$e');
}
}
}
/// HTTP响应类