1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- import 'dart:convert';
- import 'package:dio/dio.dart';
- import 'package:fis_common/http/options.dart';
- import 'package:flutter/foundation.dart';
- import 'exception.dart';
- import 'http_pool.dart';
- import 'request.dart';
- /// JSON-RPC Client 基类
- class JsonRpcClientBase {
- /// 服务主机地址
- final String host;
- late String _serviceName;
- /// 服务名称
- String get serviceName => _serviceName;
- /// 自定义Http header
- final Map<String, String>? headers;
- /// 超时时间(ms)
- final int? timeout;
- /// 服务请求地址
- String get servicePath =>
- host.endsWith('/') ? "$host$serviceName" : "$host/$serviceName";
- JsonRpcClientBase(
- this.host,
- String serviceName, {
- this.headers,
- this.timeout,
- }) {
- _serviceName = serviceName;
- }
- /// 设置服务名
- void setServiceName(String name) => _serviceName = name;
- /// 请求RPC method
- @protected
- Future<dynamic> call(String method, [args]) async {
- var request = JsonRpcRequest(method, args);
- return _transmit(request);
- }
- /// 通知 RPC method
- @protected
- void notify(String method, [args]) {
- var request = JsonRpcRequest(method, args, notify: true);
- _transmit(request);
- }
- Future<dynamic> _transmit(JsonRpcRequest request) async {
- String package = jsonEncode(request.toJson());
- var response = await _postRequest(package);
- if (response == null) throw JsonRpcException("Response Empty");
- var result = _handleDecoded(response);
- return result;
- }
- Future<dynamic> _postRequest(String package) async {
- try {
- final httpClient = jrpcHttpPool.getClient(this.host,
- timeout: this.timeout, headers: this.headers);
- var response =
- await httpClient.post('/${this.serviceName}', data: package);
- // if (response.statusCode != HttpStatus.ok) {
- if (response.statusCode != 200) {
- throw JsonRpcException("Http error", response.statusCode!);
- }
- return response.data;
- } on DioError catch (e) {
- throw JsonRpcException("Http error", 0, e);
- }
- }
- dynamic _handleDecoded(Map<String, dynamic> resp) {
- if (resp.containsKey('error')) {
- throw JsonRpcServerError.fromJson(resp['error']);
- }
- return resp['result'];
- }
- }
- abstract class JsonRpcRequestModelBase {
- /// 转成Json Map
- Map<String, dynamic> toJson();
- }
|