哥哥教你Flutter第三方库http最强封装,拿来就用,忽略证
最近Flutter项目中访问https,总是报错如下:
这是https证书问题,但一直没找到Flutter中的解决方案。所以在这里给出完整的忽略证书的基于第三方http框架的拿来就用的Flutter项目网络框架HttpUtils:
import 'package:http/http.dart' as http;
import 'dart:io';
import 'package:http/io_client.dart';
class HttpUtils {
static void get(String url, Function callback,
{Map params, Function errorCallback})async {
if (params !=null && params.isNotEmpty) {
StringBuffer sb =new StringBuffer("?");
params.forEach((key, value) {
sb.write("$key" +"=" +"$value" +"&");
});
String paramStr = sb.toString();
paramStr = paramStr.substring(0, paramStr.length -1);
url += paramStr;
}
try {
var client =ignoreCertificateClient();
http.Response res =await client.get(url);
if (callback !=null) {
callback(res.body);
}
}catch (exception) {
if (errorCallback !=null) {
errorCallback(exception);
}
}
}
static void post(String url, Function callback,
{Map params, Function errorCallback})async {
try {
var client =ignoreCertificateClient();
http.Response res =await client.post(url, body: params);
if (callback !=null) {
callback(res.body);
}
}catch (e) {
if (errorCallback !=null) {
errorCallback(e);
}
}
}
static bool_certificateCheck(X509Certificate cert, String host, int port) =>true;
static IOClientignoreCertificateClient() {
var ioClient =new HttpClient()
..badCertificateCallback =_certificateCheck;
return new IOClient(ioClient);
}
}
使用方法一句代码搞定:
HttpUtils.get('XXXXXXXXXXXXXXX.COM',(data){
if(data !=null){
final body = convert.jsonDecode(data.toString());
logger.e(body.toString());
}
});