瀏覽代碼

Add an example of using HTTPRequest to contact a REST API

We already had an example to download and display an image,
but having another example dedicated to REST APIs doesn't hurt.
Hugo Locurcio 5 年之前
父節點
當前提交
c719cea116
共有 1 個文件被更改,包括 21 次插入0 次删除
  1. 21 0
      doc/classes/HTTPRequest.xml

+ 21 - 0
doc/classes/HTTPRequest.xml

@@ -6,6 +6,27 @@
 	<description>
 	<description>
 		A node with the ability to send HTTP requests. Uses [HTTPClient] internally.
 		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.
 		Can be used to make HTTP requests, i.e. download or upload files or web content via HTTP.
+		[b]Example of contacting a REST API and printing one of its returned fields:[/b]
+		[codeblock]
+		func _ready():
+		    # Create an HTTP request node and connect its completion signal.
+		    var http_request = HTTPRequest.new()
+		    add_child(http_request)
+		    http_request.connect("request_completed", self, "_http_request_completed")
+
+		    # Perform the HTTP request. The URL below returns some 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.")
+
+
+		# Called when the HTTP request is completed.
+		func _http_request_completed(result, response_code, headers, body):
+		    var response = parse_json(body.get_string_from_utf8())
+
+		    # Will print the user agent string used by the HTTPRequest node (as recognized by httpbin.org).
+		    print(response.headers["User-Agent"])
+		[/codeblock]
 		[b]Example of loading and displaying an image using HTTPRequest:[/b]
 		[b]Example of loading and displaying an image using HTTPRequest:[/b]
 		[codeblock]
 		[codeblock]
 		func _ready():
 		func _ready():