HTTPRequest

繼承: Node < Object

具有發送 HTTP(S) 請求能力的節點。

說明

A node with the ability to send HTTP requests. Uses HTTPClient internally.

Can be used to make HTTP requests, i.e. download or upload files or web content via HTTP.

Warning: See the notes and warnings on HTTPClient for limitations, especially regarding TLS security.

Note: When exporting to Android, make sure to enable the INTERNET permission in the Android export preset before exporting the project or using one-click deploy. Otherwise, network communication of any kind will be blocked by Android.

Example: Contact a REST API and print one of its returned fields:

func _ready():
    # Create an HTTP request node and connect its completion signal.
    var http_request = HTTPRequest.new()
    add_child(http_request)
    http_request.request_completed.connect(self._http_request_completed)

    # Perform a GET request. The URL below returns JSON as of writing.
    var error = http_request.request("https://httpbin.org/get")
    if error != OK:
        push_error("An error occurred in the HTTP request.")

    # Perform a POST request. The URL below returns JSON as of writing.
    # Note: Don't make simultaneous requests using a single HTTPRequest node.
    # The snippet below is provided for reference only.
    var body = JSON.new().stringify({"name": "Godette"})
    error = http_request.request("https://httpbin.org/post", [], HTTPClient.METHOD_POST, body)
    if error != OK:
        push_error("An error occurred in the HTTP request.")

# Called when the HTTP request is completed.
func _http_request_completed(result, response_code, headers, body):
    var json = JSON.new()
    json.parse(body.get_string_from_utf8())
    var response = json.get_data()

    # Will print the user agent string used by the HTTPRequest node (as recognized by httpbin.org).
    print(response.headers["User-Agent"])

Example: Load an image using HTTPRequest and display it:

func _ready():
    # Create an HTTP request node and connect its completion signal.
    var http_request = HTTPRequest.new()
    add_child(http_request)
    http_request.request_completed.connect(self._http_request_completed)

    # Perform the HTTP request. The URL below returns a PNG image as of writing.
    var error = http_request.request("https://placehold.co/512.png")
    if error != OK:
        push_error("An error occurred in the HTTP request.")

# Called when the HTTP request is completed.
func _http_request_completed(result, response_code, headers, body):
    if result != HTTPRequest.RESULT_SUCCESS:
        push_error("Image couldn't be downloaded. Try a different image.")

    var image = Image.new()
    var error = image.load_png_from_buffer(body)
    if error != OK:
        push_error("Couldn't load the image.")

    var texture = ImageTexture.create_from_image(image)

    # Display the image in a TextureRect node.
    var texture_rect = TextureRect.new()
    add_child(texture_rect)
    texture_rect.texture = texture

Note: HTTPRequest nodes will automatically handle decompression of response bodies. An Accept-Encoding header will be automatically added to each of your requests, unless one is already specified. Any response with a Content-Encoding: gzip header will automatically be decompressed and delivered to you as uncompressed bytes.

教學

屬性

bool

accept_gzip

true

int

body_size_limit

-1

int

download_chunk_size

65536

String

download_file

""

int

max_redirects

8

float

timeout

0.0

bool

use_threads

false

方法

void

cancel_request()

int

get_body_size() const

int

get_downloaded_bytes() const

Status

get_http_client_status() const

Error

request(url: String, custom_headers: PackedStringArray = PackedStringArray(), method: Method = 0, request_data: String = "")

Error

request_raw(url: String, custom_headers: PackedStringArray = PackedStringArray(), method: Method = 0, request_data_raw: PackedByteArray = PackedByteArray())

void

set_http_proxy(host: String, port: int)

void

set_https_proxy(host: String, port: int)

void

set_tls_options(client_options: TLSOptions)


訊號

request_completed(result: int, response_code: int, headers: PackedStringArray, body: PackedByteArray) 🔗

請求完成時觸發。


列舉

enum Result: 🔗

Result RESULT_SUCCESS = 0

請求成功。

Result RESULT_CHUNKED_BODY_SIZE_MISMATCH = 1

Request failed due to a mismatch between the expected and actual chunked body size during transfer. Possible causes include network errors, server misconfiguration, or issues with chunked encoding.

Result RESULT_CANT_CONNECT = 2

連接時請求失敗。

Result RESULT_CANT_RESOLVE = 3

解析時請求失敗。

Result RESULT_CONNECTION_ERROR = 4

因連接(讀寫)錯誤而失敗。

Result RESULT_TLS_HANDSHAKE_ERROR = 5

TLS 握手時請求失敗。

Result RESULT_NO_RESPONSE = 6

請求(目前還)沒有獲得相應。

Result RESULT_BODY_SIZE_LIMIT_EXCEEDED = 7

請求超出了大小上限,見 body_size_limit

Result RESULT_BODY_DECOMPRESS_FAILED = 8

Request failed due to an error while decompressing the response body. Possible causes include unsupported or incorrect compression format, corrupted data, or incomplete transfer.

Result RESULT_REQUEST_FAILED = 9

請求失敗(目前未使用)。

Result RESULT_DOWNLOAD_FILE_CANT_OPEN = 10

HTTPRequest 無法打開下載檔案。

Result RESULT_DOWNLOAD_FILE_WRITE_ERROR = 11

HTTPRequest 無法寫入下載檔案。

Result RESULT_REDIRECT_LIMIT_REACHED = 12

請求超出了重定向次數上限,見 max_redirects

Result RESULT_TIMEOUT = 13

請求由於超時而失敗。如果本就希望請求花費較長的時間,請嘗試增大 timeout,或將其設為 0.0 從而完全移除超時。


屬性說明

bool accept_gzip = true 🔗

  • void set_accept_gzip(value: bool)

  • bool is_accepting_gzip()

If true, this header will be added to each request: Accept-Encoding: gzip, deflate telling servers that it's okay to compress response bodies.

Any Response body declaring a Content-Encoding of either gzip or deflate will then be automatically decompressed, and the uncompressed bytes will be delivered via request_completed.

If the user has specified their own Accept-Encoding header, then no header will be added regardless of accept_gzip.

If false no header will be added, and no decompression will be performed on response bodies. The raw bytes of the response body will be returned via request_completed.


int body_size_limit = -1 🔗

  • void set_body_size_limit(value: int)

  • int get_body_size_limit()

回應正文的最大允許大小。如果回應正文被壓縮,這將用作解壓縮的正文的最大允許大小。


int download_chunk_size = 65536 🔗

  • void set_download_chunk_size(value: int)

  • int get_download_chunk_size()

使用的緩衝區大小和每次反覆運算讀取的最大位元組數。參閱 HTTPClient.read_chunk_size

下載小檔時將其設定為較低的值,以降低記憶體使用量,但會降低下載速度,例如 4096 表示 4 KiB。


String download_file = "" 🔗

  • void set_download_file(value: String)

  • String get_download_file()

要下載到的檔案。將任何接收到的檔輸出到其中。


int max_redirects = 8 🔗

  • void set_max_redirects(value: int)

  • int get_max_redirects()

允許的最大重定向數。


float timeout = 0.0 🔗

  • void set_timeout(value: float)

  • float get_timeout()

請求超時前等待的秒數。如果 timeout0.0,則請求不會超時。對於簡單的請求,例如與 REST API 通信,建議將 timeout 設為與服務器回應時間配對的值(例如 1.010.0 之間)。這樣能夠防止由於伺服器回應時間的變化而造成的超時,同時仍然允許套用程式偵測到請求超時。對於大型請求,例如下載檔案,建議將 timeout 設定為 0.0 禁用超時功能。這樣有助於防止由於超時而讓大型傳輸失敗。


bool use_threads = false 🔗

  • void set_use_threads(value: bool)

  • bool is_using_threads()

true 時,將啟用多執行緒提高性能。


方法說明

void cancel_request() 🔗

取消目前請求。


int get_body_size() const 🔗

返回回應體長度。

注意:部分 Web 伺服器可能不發送回應體長度,此時返回值將為 -1。如果使用分塊傳輸編碼,回應體的長度也將為 -1


int get_downloaded_bytes() const 🔗

返回該 HTTPRequest 已下載的位元組數。


Status get_http_client_status() const 🔗

Returns the current status of the underlying HTTPClient.


Error request(url: String, custom_headers: PackedStringArray = PackedStringArray(), method: Method = 0, request_data: String = "") 🔗

在底層的 HTTPClient 上建立請求。如果沒有配置錯誤,它會嘗試使用 HTTPClient.connect_to_host() 連接並將參數傳遞給 HTTPClient.request()

如果成功建立請求,則返回 @GlobalScope.OK。(並不意味著伺服器已回應),如果不在樹中,則返回 @GlobalScope.ERR_UNCONFIGURED;如果仍在處理先前的請求,則返回 @GlobalScope.ERR_BUSY;如果給定的字串不是有效的 URL 格式,則返回 @GlobalScope.ERR_INVALID_PARAMETER;或者如果不使用執行緒並且 HTTPClient 無法連接到主機,則返回 @GlobalScope.ERR_CANT_CONNECT

注意:methodHTTPClient.METHOD_GET 時,通過 request_data 發送的有效載荷可能會被伺服器忽略,甚至導致伺服器拒絕請求(見 RFC 7231 第 4.3.1 節瞭解更多詳情)。作為一種變通方法,可以在 URL 中將資料作為查詢字串發送(有關範例,請參見 String.uri_encode())。

注意:建議使用傳輸加密(TLS)並避免在 HTTP GET URL 參數中發送敏感資訊(例如登錄憑據)。考慮改用 HTTP POST 請求或 HTTP 報頭來獲取此類資訊。


Error request_raw(url: String, custom_headers: PackedStringArray = PackedStringArray(), method: Method = 0, request_data_raw: PackedByteArray = PackedByteArray()) 🔗

在底層的HTTPClient上建立請求,使用一個原始位元組陣列作為請求主體。如果沒有配置錯誤,它會嘗試使用 HTTPClient.connect_to_host() 連接並將參數傳遞給 HTTPClient.request()

如果請求建立成功,則返回 @GlobalScope.OK。(並不意味著伺服器已回應),@GlobalScope.ERR_UNCONFIGURED 如果不在樹中,@GlobalScope.ERR_BUSY 如果仍在處理先前的請求,@GlobalScope.ERR_INVALID_PARAMETER 如果給定的字串不是有效的 URL 格式,或 @GlobalScope.ERR_CANT_CONNECT如果不使用執行緒並且 HTTPClient 無法連接到主機。


void set_http_proxy(host: String, port: int) 🔗

設定 HTTP 請求使用的代理伺服器。

如果 host 為空或者 port 為 -1,則會取消設定代理伺服器。


void set_https_proxy(host: String, port: int) 🔗

設定 HTTPS 請求使用的代理伺服器。

如果 host 為空或者 port 為 -1,則會取消設定代理伺服器。


void set_tls_options(client_options: TLSOptions) 🔗

設定連接到 HTTPS 伺服器時使用的 TLSOptions。見 TLSOptions.client()