httpc庫為內(nèi)部cf內(nèi)部實(shí)現(xiàn)的一種http client, 底層基于cf內(nèi)部的TCP connect與SSL connect實(shí)現(xiàn).
httpc庫支持http與https請(qǐng)求, 根據(jù)傳參自動(dòng)判斷是否需要進(jìn)行安全TCP握手連接;
httpc庫支持ipv4/ipv6的ip或domain進(jìn)行請(qǐng)求, 手寫ipv6需要將ipv6地址語法加入到[]內(nèi)部, 如: http://[::1]:80
;
httpc庫支持多種Method進(jìn)行http client請(qǐng)求;
httpc庫無需初始化即可使用, 支持設(shè)置httpc連接或請(qǐng)求超時(shí)設(shè)置;
全局超時(shí)時(shí)間為TIMEOUT, 默認(rèn)為15秒.
get方法將會(huì)對(duì)domain發(fā)起一次http GET請(qǐng)求.
HEADER為一個(gè)key-value數(shù)組{[1] = key, [2] = value}, 不支持Content-Type與Content-Length等設(shè)置;
ARGS為請(qǐng)求參數(shù), httpc框架將為使用者自動(dòng)構(gòu)建http GET 查詢參數(shù);
TIMEOUT為請(qǐng)求的最大超時(shí)時(shí)間(optional);
使用示例:
local code, body = httpc.get("http://localhost:8080/api?page=1&limit=10", {{"Auth", "admin"}})
local code, body = httpc.get("http://localhost:8080/api", {{"Auth", "admin"}}, {{'page', 1}, {'limit', 10}})
local code, body = httpc.get("http://localhost:8080/api", {{"Auth", "admin"}}, {{'page', 1}, {'limit', 10}}, 3)
此方法有2個(gè)返回值, code為返回的http 狀態(tài)碼, body為response body;
當(dāng)code為nil時(shí), body為出錯(cuò)信息; 當(dāng)code為number時(shí)請(qǐng)自行判斷; (不支持302與301)
post方法將會(huì)對(duì)domain發(fā)起一次http POST請(qǐng)求.
HEADER為一個(gè)key-value數(shù)組{[1] = key, [2] = value}, 不支持Content-Type與Content-Length等設(shè)置;
BODY為一個(gè)key-value數(shù)組{[1] = key, [2] = value}, Content-Type為application/x-www-form-urlencoded;
TIMEOUT為請(qǐng)求的最大超時(shí)時(shí)間(optional);
使用示例:
local code, body = httpc.post("http://[::ffff:127.0.0.1]:8080/api", {{"Auth", "admin"}}, {{'page', 1}, {'limit', 10}}, 3)
此方法有2個(gè)返回值, code為返回的http 狀態(tài)碼, body為response body;
當(dāng)code為nil時(shí), body為出錯(cuò)信息; 當(dāng)code為number時(shí)請(qǐng)自行判斷; (不支持302與301)
json方法將會(huì)對(duì)domain發(fā)起一次http POST請(qǐng)求.
HEADER為一個(gè)key-value數(shù)組{[1] = key, [2] = value}, 不支持Content-Type與Content-Length等設(shè)置;
JSON為一個(gè)json格式的字符串, 需要使用者自行進(jìn)行格式化; Content-Type為application/json;
TIMEOUT為請(qǐng)求的最大超時(shí)時(shí)間(optional);
使用示例:
local code, body = httpc.json("http://localhost:8080/api", {{"Auth", "admin"}}, json.encode({page=1, limit=10}))
此方法有2個(gè)返回值, code為返回的http 狀態(tài)碼, body為response body;
當(dāng)code為nil時(shí), body為出錯(cuò)信息; 當(dāng)code為number時(shí)請(qǐng)自行判斷; (不支持302與301)
file方法將會(huì)對(duì)domain發(fā)起一次http POST請(qǐng)求.
HEADER為一個(gè)key-value數(shù)組{[1] = key, [2] = value}, 不支持Content-Type與Content-Length等設(shè)置;
FILES為一個(gè)file數(shù)組{name = name, filename = filename, file = file}; 其中file為文件內(nèi)容, application/文件類型
TIMEOUT為請(qǐng)求的最大超時(shí)時(shí)間(optional);
使用示例:
local code, body = httpc.file('http://localhost:8080/view', nil, {
{name='1', filename='1.jpg', file='1', type='abc'},
{name='2', filename='2.jpg', file='2', type='abc'},
})
此方法有2個(gè)返回值, code為返回的http 狀態(tài)碼, body為response body;
當(dāng)code為nil時(shí), body為出錯(cuò)信息; 當(dāng)code為number時(shí)請(qǐng)自行判斷; (不支持302與301)
需要注意的事:
更多建議: