http_client_class.rst 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. .. _doc_http_client_class:
  2. HTTP client class
  3. =================
  4. :ref:`HTTPClient <class_HTTPClient>` provides low-level access to HTTP communication.
  5. For a higher-level interface, you may want to take a look at :ref:`HTTPRequest <class_HTTPRequest>` first,
  6. which has a tutorial available :ref:`here <doc_http_request_class>`.
  7. Here's an example of using the :ref:`HTTPClient <class_HTTPClient>`
  8. class. It's just a script, so it can be run by executing:
  9. .. tabs::
  10. .. code-tab:: console GDScript
  11. c:\godot> godot -s http_test.gd
  12. .. code-tab:: console C#
  13. c:\godot> godot -s HTTPTest.cs
  14. It will connect and fetch a website.
  15. .. tabs::
  16. .. code-tab:: gdscript GDScript
  17. extends SceneTree
  18. # HTTPClient demo
  19. # This simple class can do HTTP requests; it will not block, but it needs to be polled.
  20. func _init():
  21. var err = 0
  22. var http = HTTPClient.new() # Create the Client.
  23. err = http.connect_to_host("www.php.net", 80) # Connect to host/port.
  24. assert(err == OK) # Make sure connection is OK.
  25. # Wait until resolved and connected.
  26. while http.get_status() == HTTPClient.STATUS_CONNECTING or http.get_status() == HTTPClient.STATUS_RESOLVING:
  27. http.poll()
  28. print("Connecting...")
  29. if not OS.has_feature("web"):
  30. OS.delay_msec(500)
  31. else:
  32. yield(Engine.get_main_loop(), "idle_frame")
  33. assert(http.get_status() == HTTPClient.STATUS_CONNECTED) # Check if the connection was made successfully.
  34. # Some headers
  35. var headers = [
  36. "User-Agent: Pirulo/1.0 (Godot)",
  37. "Accept: */*"
  38. ]
  39. err = http.request(HTTPClient.METHOD_GET, "/ChangeLog-5.php", headers) # Request a page from the site (this one was chunked..)
  40. assert(err == OK) # Make sure all is OK.
  41. while http.get_status() == HTTPClient.STATUS_REQUESTING:
  42. # Keep polling for as long as the request is being processed.
  43. http.poll()
  44. print("Requesting...")
  45. if OS.has_feature("web"):
  46. # Synchronous HTTP requests are not supported on the web,
  47. # so wait for the next main loop iteration.
  48. yield(Engine.get_main_loop(), "idle_frame")
  49. else:
  50. OS.delay_msec(500)
  51. assert(http.get_status() == HTTPClient.STATUS_BODY or http.get_status() == HTTPClient.STATUS_CONNECTED) # Make sure request finished well.
  52. print("response? ", http.has_response()) # Site might not have a response.
  53. if http.has_response():
  54. # If there is a response...
  55. headers = http.get_response_headers_as_dictionary() # Get response headers.
  56. print("code: ", http.get_response_code()) # Show response code.
  57. print("**headers:\\n", headers) # Show headers.
  58. # Getting the HTTP Body
  59. if http.is_response_chunked():
  60. # Does it use chunks?
  61. print("Response is Chunked!")
  62. else:
  63. # Or just plain Content-Length
  64. var bl = http.get_response_body_length()
  65. print("Response Length: ", bl)
  66. # This method works for both anyway
  67. var rb = PoolByteArray() # Array that will hold the data.
  68. while http.get_status() == HTTPClient.STATUS_BODY:
  69. # While there is body left to be read
  70. http.poll()
  71. # Get a chunk.
  72. var chunk = http.read_response_body_chunk()
  73. if chunk.size() == 0:
  74. if not OS.has_feature("web"):
  75. # Got nothing, wait for buffers to fill a bit.
  76. OS.delay_usec(1000)
  77. else:
  78. yield(Engine.get_main_loop(), "idle_frame")
  79. else:
  80. rb = rb + chunk # Append to read buffer.
  81. # Done!
  82. print("bytes got: ", rb.size())
  83. var text = rb.get_string_from_ascii()
  84. print("Text: ", text)
  85. quit()
  86. .. code-tab:: csharp
  87. class HTTPTest : SceneTree
  88. {
  89. // HTTPClient demo.
  90. // This simple class can make HTTP requests; it will not block, but it needs to be polled.
  91. public override async void _Initialize()
  92. {
  93. Error err;
  94. HTTPClient http = new HTTPClient(); // Create the client.
  95. err = http.ConnectToHost("www.php.net", 80); // Connect to host/port.
  96. Debug.Assert(err == Error.Ok); // Make sure the connection is OK.
  97. // Wait until resolved and connected.
  98. while (http.GetStatus() == HTTPClient.Status.Connecting || http.GetStatus() == HTTPClient.Status.Resolving)
  99. {
  100. http.Poll();
  101. GD.Print("Connecting...");
  102. OS.DelayMsec(500);
  103. }
  104. Debug.Assert(http.GetStatus() == HTTPClient.Status.Connected); // Check if the connection was made successfully.
  105. // Some headers.
  106. string[] headers = { "User-Agent: Pirulo/1.0 (Godot)", "Accept: */*" };
  107. err = http.Request(HTTPClient.Method.Get, "/ChangeLog-5.php", headers); // Request a page from the site.
  108. Debug.Assert(err == Error.Ok); // Make sure all is OK.
  109. // Keep polling for as long as the request is being processed.
  110. while (http.GetStatus() == HTTPClient.Status.Requesting)
  111. {
  112. http.Poll();
  113. GD.Print("Requesting...");
  114. if (OS.HasFeature("web"))
  115. {
  116. // Synchronous HTTP requests are not supported on the web,
  117. // so wait for the next main loop iteration.
  118. await ToSignal(Engine.GetMainLoop(), "idle_frame");
  119. }
  120. else
  121. {
  122. OS.DelayMsec(500);
  123. }
  124. }
  125. Debug.Assert(http.GetStatus() == HTTPClient.Status.Body || http.GetStatus() == HTTPClient.Status.Connected); // Make sure the request finished well.
  126. GD.Print("Response? ", http.HasResponse()); // The site might not have a response.
  127. // If there is a response...
  128. if (http.HasResponse())
  129. {
  130. headers = http.GetResponseHeaders(); // Get response headers.
  131. GD.Print("Code: ", http.GetResponseCode()); // Show response code.
  132. GD.Print("Headers:");
  133. foreach (string header in headers)
  134. {
  135. // Show headers.
  136. GD.Print(header);
  137. }
  138. if (http.IsResponseChunked())
  139. {
  140. // Does it use chunks?
  141. GD.Print("Response is Chunked!");
  142. }
  143. else
  144. {
  145. // Or just Content-Length.
  146. GD.Print("Response Length: ", http.GetResponseBodyLength());
  147. }
  148. // This method works for both anyways.
  149. List<byte> rb = new List<byte>(); // List that will hold the data.
  150. // While there is data left to be read...
  151. while (http.GetStatus() == HTTPClient.Status.Body)
  152. {
  153. http.Poll();
  154. byte[] chunk = http.ReadResponseBodyChunk(); // Read a chunk.
  155. if (chunk.Length == 0)
  156. {
  157. // If nothing was read, wait for the buffer to fill.
  158. OS.DelayMsec(500);
  159. }
  160. else
  161. {
  162. // Append the chunk to the read buffer.
  163. rb.AddRange(chunk);
  164. }
  165. }
  166. // Done!
  167. GD.Print("Bytes Downloaded: ", rb.Count);
  168. string text = Encoding.ASCII.GetString(rb.ToArray());
  169. GD.Print(text);
  170. }
  171. Quit();
  172. }
  173. }