client_base.dart 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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(message: "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(
  60. message: "Http error.Status coder: ${response.statusCode}.");
  61. }
  62. return response.data;
  63. } on DioError catch (e) {
  64. throw JsonRpcException(message: "Http error", data: e);
  65. }
  66. }
  67. dynamic _handleDecoded(Map<String, dynamic> resp) {
  68. if (resp.containsKey('error')) {
  69. throw JsonRpcServerError.fromJson(resp['error']);
  70. }
  71. return resp['result'];
  72. }
  73. }
  74. abstract class JsonRpcRequestModelBase {
  75. /// 转成Json Map
  76. Map<String, dynamic> toJson();
  77. }