http 模块 当前包含:

  • http get
  • http post
  • http post_raw(json,xml,js,text...)

http 上传文件(暂不支持)

# Http 构建

所有的请求参数全都写在一个 p 中

--组装http 请求参数
local p = {
    param={};
    header={};
    timeout = 20;
}
--1.【必填】请求的url 地址
p.url ="http:/www.baidu.com";

--2.【选填】请求的http 头文件 可以 存在多个头描述
p.header["Content-Type"] ="application/json";
p.header["xxx"] = "xxx";
p.header["yyy"] = "yyy";

--3.【选填】请求的参数 可以存在多个参数
p.param["username"] ="12333";
p.param["password"] ="133";

--4.【选填】 请求超时时间
p.timeout = 30 --请求的超时时间 (单位 秒)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# Http 返回值

http 请求返回值为一个table 其中包含3部分值

  • code : 通常200表示服务器处理数据成功
  • body :服务器返回的主体数据
  • header:服务器返回的头文件,其中包含多条头信息
--组装http 请求参数
p={};
--1.【必填】请求的url 地址
p.url ="http:/www.baidu.com";
res = httpGet(p);
if res then
    print(res.code); --服务器返回的码值
    print(res.header); --服务器返回的 头文件
    print(res.body); -- 服务器返回的主体数据
end
1
2
3
4
5
6
7
8
9
10

# HTTP-GET

http get 请求

语法 httpGet(p)

参数:

  • url:必填,请求的http地址
--组装http 请求参数
p={};
--1.【必填】请求的url 地址
p.url ="http:/www.baidu.com";
res = httpGet(p);
if res then
    print(res.code);
    print(res.header);
    print(res.body);
end

1
2
3
4
5
6
7
8
9
10
11

# HTTP-POST form

http form 表单请求

语法

参数:

  • url:请求的地址
  • params:表单中的数据
    local p = {
        param={};
        header={};
    }
    -- 请求地址
    p.url ="http://47.104.139.55/api/game";
    p.param ["name"] ="抖音";
    p.param ["offset"] ="0";
    p.param ["limit"] ="10";

    res = httpPost(p);
    if res then
        print(res.body); --打印服务器的返回值
    end
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# HTTP-POST raw

http post raw 支持各类数据提交

对应类型请 更换 header 中的 Content-Type 类型

  • json: "application/json"
  • text: "text/plain"
  • javascript: "application/javascript"
  • html: "text/html"
  • xml: "application/xml"

语法 httpPostRaw(p)

# Http 提交json 至服务器

demo 提交 json 数据至服务器

local p = {
    param={};
    header={};
}
-- 请求地址
p.url ="http://47.101.158.163:40001/tenant/login";

--请求参数
p.param ["username"] ="qq123123";

-- 请求头
p.header["Content-Type"] ="application/json";

res = httpPostRaw(p)
-- res 为请求结果
if res then
	print(res );
else
	print(" 获取失败 " )
end

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# http 下载

可以将文件下载保存至 指定目录

path = "sdcard/1001/c.apk" -- path 为要下载的目录
url = "http://47.104.139.55/getApk"; --url 为web 下载地址
isSuccess =  httpDownload(path,url);
if isSuccess then
    print('下载成功');
end

1
2
3
4
5
6
7

# http 上传文件

可以将文件上传至指定的网址

local p = {
    header={};
    bodypart={};
}

p.url ="https://xxxx.com"; -- 上传地址
p.header["User-Agent"] ="Firefox/6.0"; --上传终端标识模拟为火狐浏览器
p.bodypart["smfile"] = "File:/sdcard/DCIM/1.png" -- 上传文件路径 一定要File:开头
local res = postUpload(p);

print(res);

1
2
3
4
5
6
7
8
9
10
11
12

# 转码

# urlEncode

汉字的 urlencode 转码

local d = "你好"
d = urlencode(d)
print(d)
1
2
3