【问题标题】:How to solve ssl certificate error with GetX and Get Connect in flutter如何在 Flutter 中使用 GetX 和 Get Connect 解决 ssl 证书错误
【发布时间】:2022-11-11 02:37:06
【问题描述】:

我正在尝试使用 Getx 服务。

这是我的 api 客户端类,因为我正在尝试使用 getx 从互联网获取数据

import 'package:flutter_application_shop/utilis/app_constance.dart';
import 'package:get/get.dart';

class ApiClient extends GetConnect implements GetxService {
  late String token;
  final String appBaseUrl;
  late Map<String, String> _mainHeaders;

  ApiClient({required this.appBaseUrl}) {
    baseUrl = appBaseUrl;
    timeout = const Duration(seconds: 30);
    token = AppConstance.TOKEN;

    _mainHeaders = {
      'Content-type': 'application/json; charset=UTF-8',
      'Authorization': 'Bearer $token',
    };
  }

  Future<Response> getData(String url) async {
    try {
      Response response = await get(url);
      return response;
    } catch (e) {
      return Response(statusCode: 1, statusText: e.toString());
    }
  }

  ///end
}

当我运行调试时,我得到了这个错误。

I/flutter ( 6967): HandshakeException: Handshake error in client (OS Error: 
I/flutter ( 6967):      CERTIFICATE_VERIFY_FAILED: unable to get local issuer certificate(handshake.cc:393))

我该如何解决这个问题?

【问题讨论】:

    标签: flutter dart https response flutter-getx


    【解决方案1】:

    这是因为请求来自不受信任的来源,为了绕过错误,请将 allowAutoSignedCert = true; 添加到扩展 GetConnet 的类中的请求中。

    例子:

    import 'package:flutter_application_shop/utilis/app_constance.dart';
    import 'package:get/get.dart';
    
    class ApiClient extends GetConnect implements GetxService {
      late String token;
      final String appBaseUrl;
      late Map<String, String> _mainHeaders;
    
      ApiClient({required this.appBaseUrl}) {
        baseUrl = appBaseUrl;
        timeout = const Duration(seconds: 30);
        token = AppConstance.TOKEN;
        allowAutoSignedCert = true; // the solution
    
        _mainHeaders = {
          'Content-type': 'application/json; charset=UTF-8',
          'Authorization': 'Bearer $token',
        };
      }
    
      Future<Response> getData(String url) async {
        try {
          Response response = await get(url);
          return response;
        } catch (e) {
          return Response(statusCode: 1, statusText: e.toString());
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-07
      • 1970-01-01
      • 2020-09-14
      • 1970-01-01
      • 1970-01-01
      • 2019-10-07
      • 1970-01-01
      • 2019-12-11
      相关资源
      最近更新 更多