client_base.dart 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import 'dart:convert';
  2. import 'package:dio/dio.dart';
  3. import 'package:fis_common/http/options.dart';
  4. import 'package:flutter/foundation.dart';
  5. import 'exception.dart';
  6. import 'http_pool.dart';
  7. import 'request.dart';
  8. /// JSON-RPC Client 基类
  9. class JsonRpcClientBase {
  10. /// 服务主机地址
  11. final String host;
  12. late String _serviceName;
  13. /// 服务名称
  14. String get serviceName => _serviceName;
  15. /// 自定义Http header
  16. final Map<String, String>? headers;
  17. /// 超时时间(ms)
  18. final int? timeout;
  19. /// 服务请求地址
  20. String get servicePath =>
  21. host.endsWith('/') ? "$host$serviceName" : "$host/$serviceName";
  22. JsonRpcClientBase(
  23. this.host,
  24. String serviceName, {
  25. this.headers,
  26. this.timeout,
  27. }) {
  28. _serviceName = serviceName;
  29. }
  30. /// 设置服务名
  31. void setServiceName(String name) => _serviceName = name;
  32. /// 请求RPC method
  33. @protected
  34. Future<dynamic> call(String method, [args]) async {
  35. var request = JsonRpcRequest(method, args);
  36. return _transmit(request);
  37. }
  38. /// 通知 RPC method
  39. @protected
  40. void notify(String method, [args]) {
  41. var request = JsonRpcRequest(method, args, notify: true);
  42. _transmit(request);
  43. }
  44. Future<dynamic> _transmit(JsonRpcRequest request) async {
  45. String package = jsonEncode(request.toJson());
  46. var response = await _postRequest(package);
  47. if (response == null) throw JsonRpcException("Response Empty");
  48. var result = _handleDecoded(response);
  49. return result;
  50. }
  51. Future<dynamic> _postRequest(String package) async {
  52. try {
  53. final httpClient = jrpcHttpPool.getClient(this.host,
  54. timeout: this.timeout, headers: this.headers);
  55. var response =
  56. await httpClient.post('/${this.serviceName}', data: package);
  57. // if (response.statusCode != HttpStatus.ok) {
  58. if (response.statusCode != 200) {
  59. throw JsonRpcException("Http error", response.statusCode!);
  60. }
  61. return response.data;
  62. } on DioError catch (e) {
  63. throw JsonRpcException("Http error", 0, e);
  64. }
  65. }
  66. dynamic _handleDecoded(Map<String, dynamic> resp) {
  67. if (resp.containsKey('error')) {
  68. throw JsonRpcServerError.fromJson(resp['error']);
  69. }
  70. return resp['result'];
  71. }
  72. }
  73. abstract class JsonRpcRequestModelBase {
  74. /// 转成Json Map
  75. Map<String, dynamic> toJson();
  76. }