Flutter API请求耗时过长求助(Postman正常但Flutter需15-25秒)
Flutter API请求耗时异常问题
在Flutter应用中发起API请求时,耗时长达15-25秒,但相同请求在Postman中仅需200-650毫秒即可完成。我尝试使用dio_http和http两种客户端,结果几乎一致。
代码实现
Flutter核心代码
import 'package:http/http.dart' as http; import 'package:dio_http/dio_http.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); runApp(MyApp()); } class MyApp extends StatelessWidget { MyApp({super.key}); Dio dioRest = Dio( BaseOptions( baseUrl: baseURL, headers: { HttpHeaders.contentTypeHeader: ContentType.json.value, }, ), ); @override Widget build(BuildContext context) { return MaterialApp( title: 'MYAPP', home: Scaffold( appBar: AppBar(title: Text("Home page")), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ MaterialButton( child: Text("Go to my profile"), color: Theme.of(context).primaryColor, onPressed: () async{ await getAllContentList(); }), MaterialButton( child: Text("Go to Accounts"), color: Theme.of(context).primaryColor, onPressed: () async{ await getAllContentListHttp(); }), ], ), ), ), ); } Future<List<dynamic>> getAllContentList() async { try { print('Api Started'); var result = await dioRest.post(baseURL+'secured/v/getAllContentList', options: Options( headers: { 'Authorization': 'bearer $token', 'Content-Type': 'application/json', }, )); print('API result :: $result'); if (result.statusCode == 200) { print('API result decoded :: ${jsonDecode(result.data)}'); return jsonDecode(result.data); } throw DioError(requestOptions: result.requestOptions); } on DioError catch (error) { if (error.response!.statusCode! >= 400) { throw AccessTokenException(message: "Token invalid or expired"); } var businessError = BusinessError.fromJson(error.response?.data); throw BusinessException(businessError, statusCode: error.response?.statusCode); } catch (error) { throw Error(); } } Future<List<dynamic>> getAllContentListHttp() async { try { print('Api Started'); Map<String, String> requestHeaders = { 'Content-Type': 'application/json', 'Authorization': 'Bearer $token', }; String stUrl = baseURL+'protected/users/getAllActiveStreamList'; final response = await http.post(Uri.parse(baseURL+'secured/v/getAllContentList'), headers: requestHeaders); print('API result :: $response'); if (response.statusCode == 200) { print('API result decoded :: ${jsonDecode(response.body)}'); return jsonDecode(response.body); } throw AccessTokenException(message: "!!!Sorry"); } on DioError catch (error) { if (error.response!.statusCode! >= 400) { throw AccessTokenException(message: "Token invalid or expired"); } var businessError = BusinessError.fromJson(error.response?.data); throw BusinessException(businessError, statusCode: error.response?.statusCode); } catch (error) { throw Error(); } } }
依赖版本
http: ^0.13.5 dio_http: ^5.0.4
内容的提问来源于stack exchange,提问作者KJEjava48
相关产品推荐
相关产品推荐

