network.request()

类型 函数
network.*
返回值 用户数据
修订 版本 2024.3703
关键词 异步, http, https, get, post
另请参阅 network.download()
network.upload()
network.cancel()
networkRequest

概述

向 URL 发起异步 HTTP 或 HTTPS 请求。此函数返回一个句柄,可以将其传递给 network.cancel() 以取消请求。

注意事项

Android

在 Android 上,您必须将 INTERNET 权限添加到 build.settings 文件中。

settings =
{
   android =
   {
      usesPermissions =
      {
         "android.permission.INTERNET",
      },
   },
}

语法

network.request( url, method, listener [, params] )
url (必填)

字符串 HTTP 请求 URL。

method (必填)

字符串 HTTP 方法;可接受的值为 "GET"(默认)、"POST""HEAD""PUT""DELETE"

listener (必填)

侦听器 在 HTTP 操作的各个阶段调用的侦听器函数。这将传递一个 networkRequest 事件。

侦听器函数可以接收以下阶段的事件

  • "began" — 第一个通知,包含估计大小(如果已知)。
  • "progress" — 中间进度通知。
  • "ended" — 最终通知,请求完成时。

默认情况下,侦听器将仅接收 "ended" 事件。如果 params.progress(见下文)为 "upload""download",则侦听器还将接收 "began""progress" 事件。

如果响应体通过使用`params.response`定向到文件,并且响应已成功写入文件,则`event.response`将包含一个指示输出文件的`filename`和`baseDirectory`的表。如果请求完成,但产生错误响应,则任何错误响应体都将作为字符串提供在`event.response`中。此行为可防止目标文件被错误响应写入/覆盖,而不是所需的有效负载。

params (可选)

指定 HTTP 请求或响应处理选项的表,包括自定义请求标头或正文。支持以下键

  • headers — 使用字符串键指定请求标头值的表。
  • body — 包含请求正文的字符串,或者,包含`filename`和可选的`baseDirectory`的表,用于指定文件的内容将用作请求正文。
  • bodyType — 指示字符串请求正文是`“text”`还是`“binary”`的字符串。如果 `params.body` 是字符串,则默认为 `“text”`;如果它是一个指定文件的表,则默认为 `“binary”`。
  • progress — 字符串值,指示所需的进度通知类型(如果有)。可以是`“upload”`或`“download”`。通知阶段包括所需进度方向的`“began”`和`“progress”`阶段事件。默认为`nil`,表示只希望`“ended”`阶段事件。
  • response — 表值,指示响应体应写入文件,并指定响应文件的 `filename` 和可选的 `baseDirectory`。如果未提供此值,则响应体将作为字符串提供。
  • timeout — 超时时间(秒)。默认为 30 秒。
  • handleRedirects 一个布尔值,指示是否需要自动重定向处理(默认)。如果您希望接收 302 响应并自行处理它们,请将其设置为 `false`。某些类型的登录方案或自定义 Cookie 处理可能需要这样做。

请注意,如果在 `params.body` 或 `params.response` 中指定了 `filename` 表,则 `baseDirectory` 是一个可选的 常量,默认为 system.DocumentsDirectory。在 `params.response` 的情况下,`baseDirectory` 不能设置为 system.ResourceDirectory,因为该目录是只读的。

示例

HTTPS/SSL
-- The following sample code contacts Google's encrypted search over SSL
-- and prints the response (in this case, the HTML source of the home page)
-- to the console.

local function networkListener( event )

    if ( event.isError ) then
        print( "Network error: ", event.response )
    else
        print ( "RESPONSE: " .. event.response )
    end
end
 
-- Access Google over SSL:
network.request( "https://encrypted.google.com", "GET", networkListener )

使用自定义标头的 HTTP POST
-- The following code demonstrates sending data via HTTP POST,
-- specifying custom request headers and request body.

local function networkListener( event )

    if ( event.isError ) then
        print( "Network error: ", event.response )
    else
        print ( "RESPONSE: " .. event.response )
    end
end

local headers = {}
 
headers["Content-Type"] = "application/x-www-form-urlencoded"
headers["Accept-Language"] = "en-US"
 
local body = "color=red&size=small"

local params = {}
params.headers = headers
params.body = body
 
network.request( "http://127.0.0.1/formhandler.php", "POST", networkListener, params )
下载文件并显示进度更新
-- The following code demonstrates how to download a file, with progress updates.

local function networkListener( event )
    if ( event.isError ) then
        print( "Network error: ", event.response )

    elseif ( event.phase == "began" ) then
        if ( event.bytesEstimated <= 0 ) then
            print( "Download starting, size unknown" )
        else
            print( "Download starting, estimated size: " .. event.bytesEstimated )
        end

    elseif ( event.phase == "progress" ) then
        if ( event.bytesEstimated <= 0 ) then
            print( "Download progress: " .. event.bytesTransferred )
        else
            print( "Download progress: " .. event.bytesTransferred .. " of estimated: " .. event.bytesEstimated )
        end
        
    elseif ( event.phase == "ended" ) then
        print( "Download complete, total bytes transferred: " .. event.bytesTransferred )
    end
end
 
local params = {}

-- Tell network.request() that we want the "began" and "progress" events:
params.progress = "download"

-- Tell network.request() that we want the output to go to a file:
params.response = {
    filename = "solar.jpg",
    baseDirectory = system.DocumentsDirectory
}
 
network.request( "http://docs.solar2d.cn/images/simulator/image-mask-base2.png", "GET", networkListener,  params )
上传文本文件
-- The following code demonstrates an HTTP post, where the request body is text from a file.
-- This example demonstrates just one possible way to upload a file. Different web servers
-- and applications support different methods of file upload. For example, some REST services
-- support upload of a binary file in the body of a PUT request. Many web servers only allow
-- file uploads using multipart/form-encoded (text) request bodies in a POST request. If you
-- are going to attempt file upload, you must first understand the specific mechanism
-- supported by the specific web server or application that you will be working with,
-- then you must form your request data and choose your request method appropriately.

local function networkListener( event )

    if ( event.isError ) then
        print( "Network error: ", event.response )
    else
        print ( "Upload complete!" )
    end
end

local headers = {}
 
headers["Content-Type"] = "application/json"
headers["X-API-Key"] = "13b6ac91a2"
 
local params = {}
params.headers = headers

-- Tell network.request() to get the request body from a file:
params.body = {
    filename = "object.json",
    baseDirectory = system.DocumentsDirectory        
}
 
network.request( "http://127.0.0.1/restapi.php", "POST", networkListener, params )