如何使用自签名证书从JSON请求中获取对象列表

时间:2019-04-05 07:04:17

标签: json dart flutter get

我正在编写一个应用程序以连接到Flutter中的Proxmox,并且需要获得各种身份验证领域。我遇到的问题是,大多数服务器都使用自签名SSL证书,而http导入不支持该证书。这迫使我使用dart:io软件包及其HttpClient。但是,使用此方法不会返回任何结果,列表为空。

D/        ( 9335): HostConnection::get() New Host Connection established 0xe047c540, tid 9354
D/EGL_emulation( 9335): eglMakeCurrent: 0xe76a7ac0: ver 3 0 (tinfo 0xccd07000)
I/flutter ( 9335): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 9335): The following NoSuchMethodError was thrown building FormField<dynamic>(dirty, state:
I/flutter ( 9335): FormFieldState<dynamic>#11694):
I/flutter ( 9335): The method 'map' was called on null.
I/flutter ( 9335): Receiver: null
I/flutter ( 9335): Tried calling: map<DropdownMenuItem<String>>(Closure: (AuthRealm) => DropdownMenuItem<String>)

这是我的 client 类:

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:Proxcontrol/Client/Objects/auth_realms.dart';

class Client {
  String baseUrl;

  Client(String url, String port) {
    baseUrl = "https://" + url + ":" + port +  "/api2/json/";
  }

  Future<List<AuthRealm>> getAuthRealms() async {
    HttpClient client = new HttpClient();
    client.badCertificateCallback =((X509Certificate cert, String host, int port) => true);

    var request = await client.getUrl(Uri.parse(baseUrl + "access/domains"));

    var response = await request.close();

    return await response.transform(Utf8Decoder()).transform(JsonDecoder()).map((json) => AuthRealm.fromJson(json)).toList();
  }
}

这是请求映射到的我的AuthRealm对象类:

class AuthRealm {
  final String type;
  final String realm;
  final String comment;

  AuthRealm({this.type, this.realm, this.comment});

  factory AuthRealm.fromJson(Map<String, dynamic> json) {
    return AuthRealm(
      type: json['type'],
      realm: json['realm'],
      comment: json['comment']
    );
  }
}

这是我尝试获取身份验证领域的地方。然后,将它们传递到新页面,并在下拉按钮中显示它们。 serverAddressserverPort字段是通过TextFields填充的。

    final nextButton = RaisedButton(
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(24)),
      onPressed: () {
        Client client = new Client(serverAddress, serverPort);
        client.getAuthRealms().then((values) {
          realms = values;
        });

        Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => ServerAuthLoginScreen(authRealms: realms)));
        },
      padding: EdgeInsets.all(10),
      color: Colors.indigoAccent,
      child: Text('NEXT', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
    );

最后是在加载该屏幕时填充了身份验证领域的下拉按钮部分。

import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:Proxcontrol/Client/Objects/auth_realms.dart';

class ServerAuthLoginScreen extends StatefulWidget {
  final List<AuthRealm> authRealms;
  const ServerAuthLoginScreen({Key key, @required this.authRealms}) : super(key: key);

  @override
  _ServerAuthLoginScreenState createState() => _ServerAuthLoginScreenState(authRealms);
}

class _ServerAuthLoginScreenState extends State<ServerAuthLoginScreen> {
  List<AuthRealm> authRealms;
  _ServerAuthLoginScreenState(this.authRealms);

  String serverRealm;

  @override
  Widget build(BuildContext context) {
    double screenWidth = MediaQuery.of(context).size.width;
    double screenHeight = MediaQuery.of(context).size.height;

    final realmSelector = FormField(
      builder: (FormFieldState state) {
        return InputDecorator(
          decoration: InputDecoration(
              icon: const Icon(FontAwesomeIcons.server),
              labelText: 'Select an Auth Realm'),
          isEmpty: serverRealm == '',
          child: new DropdownButtonHideUnderline(
              child: new DropdownButton(
                  isDense: true,
                  items: authRealms.map((AuthRealm value) {
                    return new DropdownMenuItem(
                      value: value.realm,
                        child: Text(value.realm),
                    );
                  }).toList(),
                  onChanged: (String value) {
                    setState(() {
                      serverRealm = value;
                      state.didChange(value);
                    });
                  }
              )
          ),
        );
      },
    );

    _buildVerticalLayout() {
      return ListView(
        shrinkWrap: true,
        children: <Widget>[
          Padding(
            padding: EdgeInsets.only(
                left: screenWidth / 12,
                right: screenWidth / 12,
                top: screenHeight / 30),
            child: realmSelector,
          ),
        ],
      );
    }

    return Scaffold(
        appBar: AppBar(
            title: Text('Server Connection Details'),
            centerTitle: true),
        body: _buildVerticalLayout()
    );
  }
}

这是我的测试proxmox服务器对定义的地址处的GET请求给出的结果:

{
   "data":[
      {
         "type":"ad",
         "realm":"CELESTIALDATA"
      },
      {
         "type":"pam",
         "comment":"Linux PAM standard authentication",
         "realm":"pam"
      },
      {
         "type":"pve",
         "comment":"Proxmox VE authentication server",
         "realm":"pve"
      }
   ]
}

有人可以帮助我了解问题出在哪里吗?仅供参考,几天前我才刚开始使用Dart / Flutter,所以我仍在学习这里的功能。我来自Java / C ++ / Python背景。



更新: 我根据理查德的评论修改了我的客户:

  Future<List<AuthRealm>> getAuthRealms() async {
    HttpClient client = new HttpClient();
    client.badCertificateCallback =((X509Certificate cert, String host, int port) => true);

    http.IOClient ioClient = new http.IOClient(client);
    final response = await ioClient.get(baseUrl + "access/domains");
    print(response.body);

    final data = json.decode(response.body);
    List<AuthRealm> realms = data.map((j) => AuthRealm.fromJson(j)).toList();

    return realms;
  }

但是我仍然遇到错误,我所看到的一切都无法正常工作。

I/flutter (12950): {"data":[{"type":"ad","realm":"CELESTIALDATA"},{"type":"pve","comment":"Proxmox VE authentication server","realm":"pve"},{"realm":"pam","comment":"Linux PAM standard authentication","type":"pam"}]}
E/flutter (12950): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: type '(dynamic) => AuthRealm' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform'
E/flutter (12950): #0      Client.getAuthRealms (package:Proxcontrol/Client/client.dart:70:35)
E/flutter (12950): <asynchronous suspension>

2 个答案:

答案 0 :(得分:0)

也许您应该像这样使用setState

client.getAuthRealms().then((values) {
    setState((){
        realms = values;
    });
});

在您的代码中

    final nextButton = RaisedButton(
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(24)),
      onPressed: () {
        Client client = new Client(serverAddress, serverPort);
        client.getAuthRealms().then((values) {
          setState(() {
          realms = values;
        });
        });

        Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => ServerAuthLoginScreen(authRealms: realms)));
        },
      padding: EdgeInsets.all(10),
      color: Colors.indigoAccent,
      child: Text('NEXT', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
    );

答案 1 :(得分:0)

dataMap,因此您需要访问该地图中的域列表。使用data['data']来引用该列表。

要将该解码的json位列表(List<Map<String, dynamic>>)转换为AuthRealm列表,请使用.map<AuthRealm>((j) => [something that constructs an AuthRealm]).toList()

这应该有效:

final data = json.decode(response.body);
List<AuthRealm> realms = data['data'].map<AuthRealm>((j) => AuthRealm.fromJson(j)).toList();