request.gd 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #*****************************************************************************
  2. # @file request.gd
  3. # @author MakerYang(https://www.makeryang.com)
  4. # @statement 免费课程配套开源项目,任何形式收费均为盗版
  5. #*****************************************************************************
  6. extends Node
  7. # 初始化自定义数据
  8. var http_request:HTTPRequest = HTTPRequest.new()
  9. var http_callback = null
  10. # 初始化数据结构
  11. var data = {
  12. "headers": [
  13. "Content-Type: application/json",
  14. "Account-Token: ",
  15. ]
  16. }
  17. # 请求服务器接口
  18. func on_server(path: String, method: int, parameter, callback) -> void:
  19. if !http_request.is_inside_tree():
  20. add_child(http_request)
  21. var parameter_json = JSON.stringify(parameter)
  22. data["headers"][1] = "Account-Token: " + Global.get_account_token()
  23. if http_callback and http_request.is_connected("request_completed", http_callback):
  24. http_request.request_completed.disconnect(http_callback)
  25. http_request.request_completed.connect(callback)
  26. http_callback = callback
  27. http_request.request("https://" + Global.get_server_address() + path, data["headers"], method, parameter_json)
  28. # 测试服务器接口
  29. func on_server_ping() -> void:
  30. on_server("/ping", HTTPClient.METHOD_GET, {}, func(_result, code, _headers, body):
  31. if code == 200:
  32. var response = JSON.parse_string(body.get_string_from_utf8())
  33. if response["code"] == 0:
  34. print("[服务器接口:/ping]", JSON.stringify(response))
  35. else:
  36. printerr("[服务器接口:/ping]", "服务器接口通讯失败")
  37. else:
  38. printerr("[服务器接口:/ping]", "服务器接口通讯失败")
  39. )