我正在尝试使用 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))
我该如何解决这个问题?
这是因为请求来自不受信任的来源,为了绕过错误,请在扩展
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());
}
}
}
我遇到了同样的问题,
allowAutoSignedCert = true;
在ios上工作但在android上不起作用,并且扩展GetConnect的类的on init方法如下。
class BaseProvider extends GetConnect {
@override
void onInit() {
super.onInit();
httpClient.baseUrl = ApiConstants.baseUrl;
httpClient.timeout = ApiConstants.timeOutInSeconds;
allowAutoSignedCert = true;
}
}
通过将
allowAutoSignedCert = true;
移动到 onInit() 方法的顶部,自动签名开始按预期工作:
class BaseProvider extends GetConnect {
@override
void onInit() {
allowAutoSignedCert = true; //Moved to top
super.onInit();
httpClient.baseUrl = ApiConstants.baseUrl;
httpClient.timeout = ApiConstants.timeOutInSeconds;
}
}