HTTP client class

    1. # HTTPClient demo
    2. # This simple class can do HTTP requests; it will not block, but it needs to be polled.
    3. func _init():
    4. var err = 0
    5. var http = HTTPClient.new() # Create the Client.
    6. err = http.connect_to_host("www.php.net", 80) # Connect to host/port.
    7. assert(err == OK) # Make sure connection was OK.
    8. # Wait until resolved and connected.
    9. while http.get_status() == HTTPClient.STATUS_CONNECTING or http.get_status() == HTTPClient.STATUS_RESOLVING:
    10. http.poll()
    11. print("Connecting...")
    12. OS.delay_msec(500)
    13. assert(http.get_status() == HTTPClient.STATUS_CONNECTED) # Could not connect
    14. # Some headers
    15. var headers = [
    16. "User-Agent: Pirulo/1.0 (Godot)",
    17. "Accept: */*"
    18. ]
    19. while http.get_status() == HTTPClient.STATUS_REQUESTING:
    20. # Keep polling for as long as the request is being processed.
    21. http.poll()
    22. print("Requesting...")
    23. if not OS.has_feature("web"):
    24. OS.delay_msec(500)
    25. else:
    26. # Synchronous HTTP requests are not supported on the web,
    27. # so wait for the next main loop iteration.
    28. yield(Engine.get_main_loop(), "idle_frame")
    29. assert(http.get_status() == HTTPClient.STATUS_BODY or http.get_status() == HTTPClient.STATUS_CONNECTED) # Make sure request finished well.
    30. print("response? ", http.has_response()) # Site might not have a response.
    31. if http.has_response():
    32. # If there is a response...
    33. headers = http.get_response_headers_as_dictionary() # Get response headers.
    34. print("code: ", http.get_response_code()) # Show response code.
    35. print("**headers:\\n", headers) # Show headers.
    36. # Getting the HTTP Body
    37. print("Response is Chunked!")
    38. else:
    39. # Or just plain Content-Length
    40. var bl = http.get_response_body_length()
    41. print("Response Length: ", bl)
    42. # This method works for both anyway
    43. var rb = PoolByteArray() # Array that will hold the data.
    44. while http.get_status() == HTTPClient.STATUS_BODY:
    45. # While there is body left to be read
    46. http.poll()
    47. var chunk = http.read_response_body_chunk() # Get a chunk.
    48. if chunk.size() == 0:
    49. # Got nothing, wait for buffers to fill a bit.
    50. OS.delay_usec(1000)
    51. else:
    52. rb = rb + chunk # Append to read buffer.
    53. # Done!
    54. print("bytes got: ", rb.size())
    55. var text = rb.get_string_from_ascii()
    56. print("Text: ", text)