IotTools.java 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package com.jjt.utils;
  2. import cn.hutool.http.HttpRequest;
  3. import cn.hutool.http.HttpResponse;
  4. import cn.hutool.json.JSONObject;
  5. import cn.hutool.json.JSONUtil;
  6. import lombok.extern.slf4j.Slf4j;
  7. import java.nio.charset.StandardCharsets;
  8. /**
  9. * IotTools$
  10. *
  11. * @author wukai
  12. * @date 2024/5/20 17:37
  13. */
  14. @Slf4j
  15. public class IotTools {
  16. /**
  17. * 获取接口返回值
  18. * 如果报错,则一直重试
  19. *
  20. * @param request request
  21. * @return json
  22. */
  23. public static JSONObject getData(HttpRequest request) {
  24. //连接超时时间 5秒
  25. request.setConnectionTimeout(5000);
  26. HttpResponse execute;
  27. int times = 1;
  28. while (true) {
  29. try {
  30. // 尝试执行的操作
  31. execute = response(request);
  32. // 如果操作成功,则不会执行以下代码
  33. break; // 退出循环
  34. } catch (Exception e) {
  35. e.printStackTrace();
  36. log.error("接口返回数据失败,正在第{}次重新请求!!!", times++);
  37. if (times > 5) {
  38. log.error("重新5次未获取到数据!!!");
  39. throw new RuntimeException("重试5次未获取到数据!!!");
  40. }
  41. try {
  42. Thread.sleep(500);
  43. //暂停0.5秒一直重试
  44. } catch (InterruptedException ignored) {
  45. }
  46. }
  47. }
  48. String res = new String(execute.body().getBytes(), StandardCharsets.UTF_8);
  49. return JSONUtil.parseObj(res, true);
  50. }
  51. public static HttpResponse response(HttpRequest request) throws Exception {
  52. try (HttpResponse res = request.execute()) {
  53. if (!res.isOk()) {
  54. throw new RuntimeException(res.body());
  55. }
  56. return res;
  57. }
  58. }
  59. }