Attention: Here be dragons
This is the latest
(unstable) version of this documentation, which may document features
not available in or compatible with released stable versions of Godot.
Checking the stable version of the documentation...
HTTPRequest
具有發送 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.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"])
public override void _Ready()
{
// Create an HTTP request node and connect its completion signal.
var httpRequest = new HttpRequest();
AddChild(httpRequest);
httpRequest.RequestCompleted += HttpRequestCompleted;
// Perform a GET request. The URL below returns JSON as of writing.
Error error = httpRequest.Request("https://httpbin.org/get");
if (error != Error.Ok)
{
GD.PushError("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.
string body = Json.Stringify(new Godot.Collections.Dictionary
{
{ "name", "Godette" }
});
error = httpRequest.Request("https://httpbin.org/post", null, HttpClient.Method.Post, body);
if (error != Error.Ok)
{
GD.PushError("An error occurred in the HTTP request.");
}
}
// Called when the HTTP request is completed.
private void HttpRequestCompleted(long result, long responseCode, string[] headers, byte[] body)
{
var json = new Json();
json.Parse(body.GetStringFromUtf8());
var response = json.GetData().AsGodotDictionary();
// Will print the user agent string used by the HTTPRequest node (as recognized by httpbin.org).
GD.Print((response["headers"].AsGodotDictionary())["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
public override void _Ready()
{
// Create an HTTP request node and connect its completion signal.
var httpRequest = new HttpRequest();
AddChild(httpRequest);
httpRequest.RequestCompleted += HttpRequestCompleted;
// Perform the HTTP request. The URL below returns a PNG image as of writing.
Error error = httpRequest.Request("https://placehold.co/512.png");
if (error != Error.Ok)
{
GD.PushError("An error occurred in the HTTP request.");
}
}
// Called when the HTTP request is completed.
private void HttpRequestCompleted(long result, long responseCode, string[] headers, byte[] body)
{
if (result != (long)HttpRequest.Result.Success)
{
GD.PushError("Image couldn't be downloaded. Try a different image.");
}
var image = new Image();
Error error = image.LoadPngFromBuffer(body);
if (error != Error.Ok)
{
GD.PushError("Couldn't load the image.");
}
var texture = ImageTexture.CreateFromImage(image);
// Display the image in a TextureRect node.
var textureRect = new TextureRect();
AddChild(textureRect);
textureRect.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.
教學
屬性
|
||
|
||
|
||
|
||
|
||
|
||
|
方法
void |
|
get_body_size() const |
|
get_downloaded_bytes() const |
|
get_http_client_status() const |
|
request(url: String, custom_headers: PackedStringArray = PackedStringArray(), method: Method = 0, request_data: String = "") |
|
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 從而完全移除超時。
屬性說明
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 download_chunk_size = 65536 🔗
使用的緩衝區大小和每次反覆運算讀取的最大位元組數。參閱 HTTPClient.read_chunk_size。
下載小檔時將其設定為較低的值,以降低記憶體使用量,但會降低下載速度,例如 4096 表示 4 KiB。
要下載到的檔案。將任何接收到的檔輸出到其中。
允許的最大重定向數。
The duration to wait before a request times out, in seconds (independent of Engine.time_scale). If timeout is set to 0.0, the request will never time out.
For simple requests, such as communication with a REST API, it is recommended to set timeout to a value suitable for the server response time (commonly between 1.0 and 10.0). This will help prevent unwanted timeouts caused by variation in response times while still allowing the application to detect when a request has timed out. For larger requests such as file downloads, it is recommended to set timeout to 0.0, disabling the timeout functionality. This will help prevent large transfers from failing due to exceeding the timeout value.
為 true 時,將啟用多執行緒提高性能。
方法說明
void cancel_request() 🔗
取消目前請求。
返回回應體長度。
注意:部分 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。
注意:當 method 為 HTTPClient.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()。