HTTPC

2019-04-02 11:43 更新

httpc庫

httpc庫為內部cf內部實現(xiàn)的一種http client, 底層基于cf內部的TCP connect與SSL connect實現(xiàn).

httpc庫支持http與https請求, 根據(jù)傳參自動判斷是否需要進行安全TCP握手連接;

httpc庫支持ipv4/ipv6的ip或domain進行請求, 手寫ipv6需要將ipv6地址語法加入到[]內部, 如: http://[::1]:80;

httpc庫支持多種Method進行http client請求;

httpc庫無需初始化即可使用, 支持設置httpc連接或請求超時設置;

httpc的全局TIMEOUT時間

全局超時時間為TIMEOUT, 默認為15秒.

httpc.get(domain, HEADER, ARGS, TIMEOUT)

get方法將會對domain發(fā)起一次http GET請求.

HEADER為一個key-value數(shù)組{[1] = key, [2] = value}, 不支持Content-Type與Content-Length等設置;

ARGS為請求參數(shù), httpc框架將為使用者自動構建http GET 查詢參數(shù);

TIMEOUT為請求的最大超時時間(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個返回值, code為返回的http 狀態(tài)碼, body為response body;

當code為nil時, body為出錯信息; 當code為number時請自行判斷; (不支持302與301)

httpc.post(domain, HEADER, BODY, TIMEOUT)

post方法將會對domain發(fā)起一次http POST請求.

HEADER為一個key-value數(shù)組{[1] = key, [2] = value}, 不支持Content-Type與Content-Length等設置;

BODY為一個key-value數(shù)組{[1] = key, [2] = value}, Content-Type為application/x-www-form-urlencoded;

TIMEOUT為請求的最大超時時間(optional);

使用示例:

  local code, body = httpc.post("http://[::ffff:127.0.0.1]:8080/api", {{"Auth", "admin"}}, {{'page', 1}, {'limit', 10}}, 3)

此方法有2個返回值, code為返回的http 狀態(tài)碼, body為response body;

當code為nil時, body為出錯信息; 當code為number時請自行判斷; (不支持302與301)

httpc.json(domain, HEADER, JSON, TIMEOUT)

json方法將會對domain發(fā)起一次http POST請求.

HEADER為一個key-value數(shù)組{[1] = key, [2] = value}, 不支持Content-Type與Content-Length等設置;

JSON為一個json格式的字符串, 需要使用者自行進行格式化; Content-Type為application/json;

TIMEOUT為請求的最大超時時間(optional);

使用示例:

  local code, body = httpc.json("http://localhost:8080/api", {{"Auth", "admin"}}, json.encode({page=1, limit=10}))

此方法有2個返回值, code為返回的http 狀態(tài)碼, body為response body;

當code為nil時, body為出錯信息; 當code為number時請自行判斷; (不支持302與301)

httpc.file(domain, HEADER, FILES, TIMEOUT)

file方法將會對domain發(fā)起一次http POST請求.

HEADER為一個key-value數(shù)組{[1] = key, [2] = value}, 不支持Content-Type與Content-Length等設置;

FILES為一個file數(shù)組{name = name, filename = filename, file = file}; 其中file為文件內容, application/文件類型

TIMEOUT為請求的最大超時時間(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個返回值, code為返回的http 狀態(tài)碼, body為response body;

當code為nil時, body為出錯信息; 當code為number時請自行判斷; (不支持302與301)

最后

需要注意的事:

  • httpc不會為用戶解析response body;

  • 不支持重定向自行跳轉, 需要使用者自行解決與判斷;

  • 暫時不支持除以上API外的其它請求方法;
以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號