Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

有没有大佬帮我看看我的代码有什么问题,handler.resolve(res) 后,原始请求返回值一直为空,不知道为什么? #2089

Closed
jackie-weiwei opened this issue Jan 9, 2024 · 1 comment

Comments

@jackie-weiwei
Copy link

`import 'dart:io';
import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class RestApi {
late Dio _dio;
late Dio _dio2;
late String _token;
late String _token2;

get dio => _dio;
static final RestApi _instance = RestApi._interal();
factory RestApi() => _instance;
RestApi._interal() {
_dio = Dio();
_dio2 = Dio();
}

void readToken() async {
SharedPreferences pref = await SharedPreferences.getInstance();
String? token = pref.getString("token");
String? token2 = pref.getString("token2");

if (token == null) {
  _token = "";
}
if (token2 == null) {
  _token2 = "";
}

}

void saveToken() async {
SharedPreferences pref = await SharedPreferences.getInstance();
pref.setString("token", _token);
pref.setString("token2", _token2);
}

init(
{String? baseUrl,
int? connectTmo,
int? receiveTmo,
int? sendTmo,
String? pem}) async {
readToken();
baseUrl = baseUrl ?? "";
connectTmo = connectTmo ?? 0;
receiveTmo = receiveTmo ?? 0;
sendTmo = sendTmo ?? 0;

BaseOptions option = BaseOptions(
    baseUrl: baseUrl,
    connectTimeout: Duration(seconds: connectTmo),
    receiveTimeout: Duration(seconds: receiveTmo),
    sendTimeout: Duration(seconds: sendTmo));

_dio = Dio(option);
_dio2 = Dio(option);

if (pem != null) {
  _dio.httpClientAdapter = IOHttpClientAdapter(
    createHttpClient: () {
      final client = HttpClient(
        context: SecurityContext(withTrustedRoots: false),
      );
      client.badCertificateCallback = (cert, host, port) => true;
      return client;
    },
    validateCertificate: (cert, host, port) {
      if (cert == null) return false;
      return cert.pem == pem;
    },
  );

  _dio2.httpClientAdapter = IOHttpClientAdapter(
    createHttpClient: () {
      final client = HttpClient(
        context: SecurityContext(withTrustedRoots: false),
      );
      client.badCertificateCallback = (cert, host, port) => true;
      return client;
    },
    validateCertificate: (cert, host, port) {
      if (cert == null) return false;
      return cert.pem == pem;
    },
  );
}
_dio.interceptors.add(QueuedInterceptorsWrapper(
  onRequest: (options, handler) async {
    options.headers["access"] = _token;
    return handler.next(options); //continue
  },
  onResponse: (response, handler) {
    debugPrint(response.requestOptions.path);

    String path = response.requestOptions.path;
    if (path.contains("login")) {
      _token = response.data["accessToken"];
      _token2 = response.data["refreshToken"];

      debugPrint(response.data);
    }
    return handler.next(response); // continue
  },
  onError: (error, handler) async {
    if (error.response?.statusCode == 401) {
      bool bSucc = await refreshToken();

      if (bSucc) {
        var res = await _dio.fetch(error.response!.requestOptions);
        handler.resolve(res); //continue
      } else {
        handler.next(error);
      }
    } else {
      handler.next(error);
    }
  },
));

}

Future post({
required String path,
dynamic data,
Map<String, dynamic>? queryParameters,
}) {
Options options = Options(
method: "post",
);

return _dio.request(
  path,
  data: data,
  queryParameters: queryParameters,
  options: options,
);

}

Future refreshToken() async {
Options options = Options(
method: "post",
headers: {"refresh": _token2},
);

Response response = await _dio2.request(
  "/refresh_token/refresh",
  data: {"mobile": "13810071252"},
  options: options,
);

_token = response.data["access"];
return true;
// try {} on DioException catch (_) {
//   return false;
// } finally {}

}
}
`

@github-actions github-actions bot closed this as completed Jan 9, 2024
Copy link
Contributor

github-actions bot commented Jan 9, 2024

@jackie-weiwei Infra and blank issues are only available for moderators. You're apperantly using the wrong issue template.

Infra 和空白 issue 仅供管理人员使用,请选择其他 issue 模板创建 issue。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant