lua发送带参数的get请求
时间: 2023-09-14 18:10:58 浏览: 111
在 Lua 中发送带参数的 GET 请求,可以将参数拼接到 URL 后面。以下是一个示例代码:
```lua
local http = require("socket.http")
local url = "https://www.example.com?param1=value1¶m2=value2"
local response, code = http.request(url)
if code == 200 then
print(response)
else
print("Request failed with error code:", code)
end
```
上述代码中,将参数拼接到 URL 后面,然后使用 `http.request` 方法发送请求。
如果参数值中包含特殊字符,需要将其进行 URL 编码,可以使用 Lua 中的 `urlencode` 函数。以下是一个示例代码:
```lua
local function urlencode(str)
if str then
str = string.gsub(str, "\n", "\r\n")
str = string.gsub(str, "([^%w ])", function(c)
return string.format("%%%02X", string.byte(c))
end)
str = string.gsub(str, " ", "+")
end
return str
end
local http = require("socket.http")
local param1 = "hello world"
local param2 = "lua is awesome"
local url = string.format("https://www.example.com?param1=%s¶m2=%s", urlencode(param1), urlencode(param2))
local response, code = http.request(url)
if code == 200 then
print(response)
else
print("Request failed with error code:", code)
end
```
上述代码中,将参数值传递给 `urlencode` 函数进行 URL 编码,然后拼接到 URL 后面发送请求。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)