httpplus.lua 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. --[[
  2. @module httpplus
  3. @summary http库的补充
  4. @version 1.0
  5. @date 2023.11.23
  6. @author wendal
  7. @demo httpplus
  8. @tag LUAT_USE_NETWORK
  9. @usage
  10. -- 本库支持的功能有:
  11. -- 1. 大文件上传的问题,不限大小
  12. -- 2. 任意长度的header设置
  13. -- 3. 任意长度的body设置
  14. -- 4. 鉴权URL自动识别
  15. -- 5. body使用zbuff返回,可直接传输给uart等库
  16. -- 与http库的差异
  17. -- 1. 不支持文件下载
  18. -- 2. 不支持fota
  19. -- 支持 http 1.0 和 http 1.1, 不支持http2.0
  20. -- 支持 GET/POST/PUT/DELETE/HEAD 等常用方法,也支持自定义method
  21. -- 支持 HTTP 和 HTTPS 协议
  22. -- 支持 IPv4 和 IPv6
  23. -- 支持 HTTP 鉴权
  24. -- 支持 multipart/form-data 上传文件和表单
  25. -- 支持 application/x-www-form-urlencoded 上传表单
  26. -- 支持 application/json 上传json数据
  27. -- 支持 自定义 body 上传任意数据
  28. -- 支持 自定义 headers
  29. -- 支持 大文件上传,不限大小
  30. -- 支持 zbuff 作为 body 上传和响应返回
  31. -- 支持 bodyfile 直接把文件内容作为body上传
  32. -- 支持 上传时使用自定义缓冲区, 2025.9.25 新增
  33. ]]
  34. local httpplus = {}
  35. local TAG = "httpplus"
  36. local function http_opts_parse(opts)
  37. if not opts then
  38. log.error(TAG, "opts不能为nil")
  39. return -100, "opts不能为nil"
  40. end
  41. if not opts.url or #opts.url < 5 then
  42. log.error(TAG, "URL不存在或者太短了", url)
  43. return -100, "URL不存在或者太短了"
  44. end
  45. if not opts.headers then
  46. opts.headers = {}
  47. end
  48. if opts.debug or httpplus.debug then
  49. if not opts.log then
  50. opts.log = log.debug
  51. end
  52. else
  53. opts.log = function()
  54. -- log.info(TAG, "无日志")
  55. end
  56. end
  57. -- 解析url
  58. -- 先判断协议是否加密
  59. local is_ssl = false
  60. local tmp = ""
  61. if opts.url:startsWith("https://") then
  62. is_ssl = true
  63. tmp = opts.url:sub(9)
  64. elseif opts.url:startsWith("http://") then
  65. tmp = opts.url:sub(8)
  66. else
  67. tmp = opts.url
  68. end
  69. -- log.info("http分解阶段1", is_ssl, tmp)
  70. -- 然后判断host段
  71. local uri = ""
  72. local host = ""
  73. local port = 0
  74. if tmp:find("/") then
  75. uri = tmp:sub((tmp:find("/"))) -- 注意find会返回多个值
  76. tmp = tmp:sub(1, tmp:find("/") - 1)
  77. else
  78. uri = "/"
  79. end
  80. -- log.info("http分解阶段2", is_ssl, tmp, uri)
  81. if tmp == nil or #tmp == 0 then
  82. log.error(TAG, "非法的URL", url)
  83. return -101, "非法的URL"
  84. end
  85. -- 有无鉴权信息
  86. if tmp:find("@") then
  87. local auth = tmp:sub(1, tmp:find("@") - 1)
  88. if not opts.headers["Authorization"] then
  89. opts.headers["Authorization"] = "Basic " .. auth:toBase64()
  90. end
  91. -- log.info("http鉴权信息", auth, opts.headers["Authorization"])
  92. tmp = tmp:sub(tmp:find("@") + 1)
  93. end
  94. -- 解析端口
  95. if tmp:find(":") then
  96. host = tmp:sub(1, tmp:find(":") - 1)
  97. port = tmp:sub(tmp:find(":") + 1)
  98. port = tonumber(port)
  99. else
  100. host = tmp
  101. end
  102. if not port or port < 1 then
  103. if is_ssl then
  104. port = 443
  105. else
  106. port = 80
  107. end
  108. end
  109. -- 收尾工作
  110. if not opts.headers["Host"] then
  111. opts.headers["Host"] = string.format("%s:%d", host, port)
  112. end
  113. -- Connection 必须关闭
  114. opts.headers["Connection"] = "Close"
  115. -- 复位一些变量,免得判断出错
  116. opts.is_closed = nil
  117. opts.body_len = 0
  118. -- multipart需要boundary
  119. local boundary = "------------------------16ef6e68ef" .. tostring(os.time())
  120. opts.boundary = boundary
  121. opts.mp = {}
  122. if opts.files then
  123. -- 强制设置为true
  124. opts.multipart = true
  125. end
  126. -- 表单数据
  127. if opts.forms then
  128. if opts.multipart then
  129. for kk, vv in pairs(opts.forms) do
  130. local tmp = string.format("--%s\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n", boundary, kk)
  131. table.insert(opts.mp, {vv, tmp, "form"})
  132. opts.body_len = opts.body_len + #tmp + #vv + 2
  133. -- log.info("当前body长度", opts.body_len, "数据长度", #vv)
  134. end
  135. else
  136. if not opts.headers["Content-Type"] then
  137. opts.headers["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8"
  138. end
  139. local buff = zbuff.create(120)
  140. for kk, vv in pairs(opts.forms) do
  141. buff:copy(nil, kk)
  142. buff:copy(nil, "=")
  143. buff:copy(nil, string.urlEncode(tostring(vv)))
  144. buff:copy(nil, "&")
  145. end
  146. if buff:used() > 0 then
  147. buff:del(-1, 1)
  148. opts.body = buff
  149. opts.body_len = buff:used()
  150. opts.log(TAG, "普通表单", opts.body)
  151. end
  152. end
  153. end
  154. if opts.files then
  155. -- 强制设置为true
  156. opts.multipart = true
  157. local contentType =
  158. {
  159. txt = "text/plain", -- 文本
  160. jpg = "image/jpeg", -- JPG 格式图片
  161. jpeg = "image/jpeg", -- JPEG 格式图片
  162. png = "image/png", -- PNG 格式图片
  163. gif = "image/gif", -- GIF 格式图片
  164. html = "image/html", -- HTML
  165. json = "application/json", -- JSON
  166. mp4 = "video/mp4", -- MP4 格式视频
  167. mp3 = "audio/mp3", -- MP3 格式音频
  168. webm = "video/webm", -- WebM 格式视频
  169. }
  170. for kk, vv in pairs(opts.files) do
  171. local ct = contentType[vv:match("%.(%w+)$")] or "application/octet-stream"
  172. local fname = vv:match("[^%/]+%w$")
  173. local tmp = string.format("--%s\r\nContent-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\nContent-Type: %s\r\n\r\n", boundary, kk, fname, ct)
  174. -- log.info("文件传输头", tmp)
  175. table.insert(opts.mp, {vv, tmp, "file"})
  176. opts.body_len = opts.body_len + #tmp + io.fileSize(vv) + 2
  177. -- log.info("当前body长度", opts.body_len, "文件长度", io.fileSize(vv), fname, ct)
  178. end
  179. end
  180. -- 如果multipart模式
  181. if opts.multipart then
  182. -- 如果没主动设置body, 那么补个结尾
  183. if not opts.body then
  184. opts.body_len = opts.body_len + #boundary + 2 + 2 + 2
  185. end
  186. -- Content-Type没设置? 那就设置一下
  187. if not opts.headers["Content-Type"] then
  188. opts.headers["Content-Type"] = "multipart/form-data; boundary="..boundary
  189. end
  190. end
  191. -- 直接设置bodyfile
  192. if opts.bodyfile then
  193. local fd = io.open(opts.bodyfile, "rb")
  194. if not fd then
  195. log.error("httpplus", "bodyfile失败,文件不存在", opts.bodyfile)
  196. return -104, "bodyfile失败,文件不存在"
  197. end
  198. fd:close()
  199. opts.body_len = io.fileSize(opts.bodyfile)
  200. end
  201. -- 有设置body, 而且没设置长度
  202. if opts.body and (not opts.body_len or opts.body_len == 0) then
  203. -- body是zbuff的情况
  204. if type(opts.body) == "userdata" then
  205. opts.body_len = opts.body:used()
  206. -- body是json的情况
  207. elseif type(opts.body) == "table" then
  208. opts.body = json.encode(opts.body, "7f")
  209. if opts.body then
  210. opts.body_len = #opts.body
  211. if not opts.headers["Content-Type"] then
  212. opts.headers["Content-Type"] = "application/json;charset=UTF-8"
  213. opts.log(TAG, "JSON", opts.body)
  214. end
  215. end
  216. -- 其他情况就只能当文本了
  217. else
  218. opts.body = tostring(opts.body)
  219. opts.body_len = #opts.body
  220. end
  221. end
  222. -- 一定要设置Content-Length,而且强制覆盖客户自定义的值
  223. -- opts.body_len = opts.body_len or 0
  224. opts.headers["Content-Length"] = tostring(opts.body_len or 0)
  225. -- 如果没设置method, 自动补齐
  226. if not opts.method or #opts.method == 0 then
  227. if opts.body_len > 0 then
  228. opts.method = "POST"
  229. else
  230. opts.method = "GET"
  231. end
  232. else
  233. -- 确保一定是大写字母
  234. opts.method = opts.method:upper()
  235. end
  236. if opts.debug then
  237. opts.log(TAG, is_ssl, host, port, uri, json.encode(opts.headers))
  238. end
  239. -- 把剩余的属性设置好
  240. opts.host = host
  241. opts.port = port
  242. opts.uri = uri
  243. opts.is_ssl = is_ssl
  244. if not opts.timeout or opts.timeout == 0 then
  245. opts.timeout = 30
  246. end
  247. return -- 成功完成,不需要返回值
  248. end
  249. local function zbuff_find(buff, str)
  250. -- log.info("zbuff查找", buff:used(), #str)
  251. if buff:used() < #str then
  252. return
  253. end
  254. local maxoff = buff:used()
  255. maxoff = maxoff - #str
  256. local tmp = zbuff.create(#str)
  257. tmp:write(str)
  258. -- log.info("tmp数据", tmp:query():toHex())
  259. for i = 0, maxoff, 1 do
  260. local flag = true
  261. for j = 0, #str - 1, 1 do
  262. -- log.info("对比", i, j, string.char(buff[i+j]):toHex(), string.char(tmp[j]):toHex(), buff[i+j] ~= tmp[j])
  263. if buff[i+j] ~= tmp[j] then
  264. flag = false
  265. break
  266. end
  267. end
  268. if flag then
  269. return i
  270. end
  271. end
  272. end
  273. local function resp_parse(opts)
  274. -- log.info("这里--------")
  275. local header_offset = zbuff_find(opts.rx_buff, "\r\n\r\n")
  276. -- log.info("头部偏移量", header_offset)
  277. if not header_offset then
  278. log.warn(TAG, "没有检测到http响应头部,非法响应")
  279. opts.resp_code = -198
  280. return
  281. end
  282. local state_line_offset = zbuff_find(opts.rx_buff, "\r\n")
  283. local state_line = opts.rx_buff:query(0, state_line_offset)
  284. local tmp = state_line:split(" ")
  285. if not tmp or #tmp < 2 then
  286. log.warn(TAG, "非法的响应行", state_line)
  287. opts.resp_code = -197
  288. return
  289. end
  290. local code = tonumber(tmp[2])
  291. if not code then
  292. log.warn(TAG, "非法的响应码", tmp[2])
  293. opts.resp_code = -196
  294. return
  295. end
  296. opts.resp_code = code
  297. opts.resp = {
  298. headers = {}
  299. }
  300. opts.log(TAG, "state code", code)
  301. -- TODO 解析header和body
  302. opts.rx_buff:del(0, state_line_offset + 2)
  303. -- opts.log(TAG, "剩余的响应体", opts.rx_buff:query())
  304. -- 解析headers
  305. while 1 do
  306. local offset = zbuff_find(opts.rx_buff, "\r\n")
  307. if not offset then
  308. log.warn(TAG, "不合法的剩余headers", opts.rx_buff:query())
  309. break
  310. end
  311. if offset == 0 then
  312. -- header的最后一个空行
  313. opts.rx_buff:del(0, 2)
  314. break
  315. end
  316. local line = opts.rx_buff:query(0, offset)
  317. opts.rx_buff:del(0, offset + 2)
  318. local tmp2 = line:split(":")
  319. opts.log(TAG, tmp2[1]:trim(), tmp2[2]:trim())
  320. opts.resp.headers[tmp2[1]:trim()] = tmp2[2]:trim()
  321. end
  322. -- if opts.resp_code < 299 then
  323. -- 解析body
  324. -- 有Content-Length就好办
  325. if opts.resp.headers["Content-Length"] then
  326. opts.log(TAG, "有长度, 标准的咯")
  327. opts.resp.body = opts.rx_buff
  328. elseif opts.resp.headers["Transfer-Encoding"] == "chunked" then
  329. -- log.info(TAG, "数据是chunked编码", opts.rx_buff[0], opts.rx_buff[1])
  330. -- log.info(TAG, "数据是chunked编码", opts.rx_buff:query(0, 4):toHex())
  331. local coffset = 0
  332. local crun = true
  333. while crun and coffset < opts.rx_buff:used() do
  334. -- 从当前offset读取长度, 长度总不会超过8字节吧?
  335. local flag = true
  336. -- local coffset = zbuff_find(opts.rx_buff, "\r\n")
  337. -- if not coffset then
  338. -- end
  339. for i = 1, 8, 1 do
  340. if opts.rx_buff[coffset+i] == 0x0D and opts.rx_buff[coffset+i+1] == 0x0A then
  341. local ctmp = opts.rx_buff:query(coffset, i)
  342. -- opts.log(TAG, "chunked分片长度", ctmp, ctmp:toHex())
  343. local clen = tonumber(ctmp, 16)
  344. -- opts.log(TAG, "chunked分片长度2", clen)
  345. if clen == nil or clen == 0 then
  346. -- 末尾了
  347. opts.rx_buff:resize(coffset)
  348. crun = false
  349. else
  350. -- 先删除chunked块
  351. opts.rx_buff:del(coffset, i+2)
  352. coffset = coffset + clen
  353. end
  354. flag = false
  355. break
  356. end
  357. end
  358. -- 肯定能搜到chunked
  359. if flag then
  360. log.error("非法的chunked块")
  361. break
  362. end
  363. end
  364. opts.resp.body = opts.rx_buff
  365. end
  366. -- end
  367. -- 清空rx_buff
  368. opts.rx_buff = nil
  369. -- 完结散花
  370. end
  371. -- socket 回调函数
  372. local function http_socket_cb(opts, event)
  373. opts.log(TAG, "tcp.event", event)
  374. if event == socket.ON_LINE then
  375. -- TCP链接已建立, 那就可以上行了
  376. -- opts.state = "ON_LINE"
  377. sys.publish(opts.topic)
  378. elseif event == socket.TX_OK then
  379. -- 数据传输完成, 如果是文件上传就需要这个消息
  380. -- opts.state = "TX_OK"
  381. sys.publish(opts.topic)
  382. elseif event == socket.EVENT then
  383. -- 收到数据或者链接断开了, 这里总需要读取一次才知道
  384. local succ, data_len = socket.rx(opts.netc, opts.rx_buff)
  385. if succ and data_len > 0 then
  386. opts.log(TAG, "收到数据", data_len, "总长", #opts.rx_buff)
  387. -- opts.log(TAG, "数据", opts.rx_buff:query())
  388. else
  389. if not opts.is_closed then
  390. opts.log(TAG, "服务器已经断开了连接或接收出错")
  391. opts.is_closed = true
  392. sys.publish(opts.topic)
  393. end
  394. end
  395. elseif event == socket.CLOSED then
  396. log.info(TAG, "连接已关闭")
  397. opts.is_closed = true
  398. sys.publish(opts.topic)
  399. end
  400. end
  401. local function http_exec(opts)
  402. local netc = socket.create(opts.adapter, function(sc, event)
  403. if opts.netc then
  404. return http_socket_cb(opts, event)
  405. end
  406. end)
  407. if not netc then
  408. log.error(TAG, "创建socket失败了!!")
  409. return -102
  410. end
  411. opts.netc = netc
  412. opts.rx_buff = zbuff.create(1024)
  413. opts.topic = tostring(netc)
  414. socket.config(netc, nil,nil, opts.is_ssl)
  415. if opts.debug or httpplus.debug then
  416. socket.debug(netc)
  417. end
  418. if not socket.connect(netc, opts.host, opts.port, opts.try_ipv6) then
  419. log.warn(TAG, "调用socket.connect返回错误了")
  420. return -103, "调用socket.connect返回错误了"
  421. end
  422. local ret = sys.waitUntil(opts.topic, 5000)
  423. if ret == false then
  424. log.warn(TAG, "建立连接超时了!!!")
  425. return -104, "建立连接超时了!!!"
  426. end
  427. -- 首先是头部
  428. local line = string.format("%s %s HTTP/1.1\r\n", opts.method:upper(), opts.uri)
  429. -- opts.log(TAG, line)
  430. socket.tx(netc, line)
  431. for k, v in pairs(opts.headers) do
  432. line = string.format("%s: %s\r\n", k, v)
  433. socket.tx(netc, line)
  434. end
  435. line = "\r\n"
  436. socket.tx(netc, line)
  437. -- 然后是body
  438. local rbody = ""
  439. local write_counter = 0
  440. local fbuf = nil
  441. if opts.upload_buff then
  442. fbuf = opts.upload_buff
  443. else
  444. if rtos.bsp():startsWith("Air8000") or rtos.bsp():startsWith("Air780EHM") then
  445. fbuf = zbuff.create(1024 * 128, 0, zbuff.HEAP_PSRAM) -- 718hm可以128k的,放手去用
  446. else
  447. fbuf = zbuff.create(1024 * 24, 0, zbuff.HEAP_PSRAM) -- 其他模组就是小的用吧
  448. end
  449. end
  450. if fbuf == nil then
  451. fbuf = zbuff.create(1024 * 8, 0, zbuff.HEAP_PSRAM) -- 创建一个小的,作为防御
  452. if fbuf == nil then
  453. fbuf = zbuff.create(1500, 0, zbuff.HEAP_PSRAM) -- 创建一个最小的,最后防御
  454. end
  455. end
  456. if opts.mp and #opts.mp > 0 then
  457. opts.log(TAG, "执行mulitpart上传模式")
  458. for k, v in pairs(opts.mp) do
  459. socket.tx(netc, v[2])
  460. write_counter = write_counter + #v[2]
  461. if v[3] == "file" then
  462. -- log.info("写入文件数据头", v[2])
  463. local fd = io.open(v[1], "rb")
  464. -- log.info("写入文件数据", v[1])
  465. if fd then
  466. while not opts.is_closed do
  467. fbuf:seek(0)
  468. local ok, flen = fd:fill(fbuf)
  469. if not ok or flen <= 0 then
  470. break
  471. end
  472. fbuf:seek(flen)
  473. -- log.info("写入文件数据", "长度", #fdata)
  474. socket.tx(netc, fbuf)
  475. write_counter = write_counter + flen
  476. -- 注意, 这里要等待TX_OK事件
  477. sys.waitUntil(opts.topic, 300)
  478. end
  479. fd:close()
  480. end
  481. else
  482. socket.tx(netc, v[1])
  483. write_counter = write_counter + #v[1]
  484. end
  485. socket.tx(netc, "\r\n")
  486. write_counter = write_counter + 2
  487. end
  488. -- rbody = rbody .. "--" .. opts.boundary .. "--\r\n"
  489. socket.tx(netc, "--")
  490. socket.tx(netc, opts.boundary)
  491. socket.tx(netc, "--\r\n")
  492. write_counter = write_counter + #opts.boundary + 2 + 2 + 2
  493. elseif opts.bodyfile then
  494. local fd = io.open(opts.bodyfile, "rb")
  495. -- log.info("写入文件数据", v[1])
  496. if fd then
  497. while not opts.is_closed do
  498. fbuf:seek(0)
  499. local ok, flen = fd:fill(fbuf)
  500. if not ok or flen <= 0 then
  501. break
  502. end
  503. fbuf:seek(flen)
  504. -- log.info("写入文件数据", "长度", #fdata)
  505. socket.tx(netc, fbuf)
  506. write_counter = write_counter + flen
  507. -- 注意, 这里要等待TX_OK事件
  508. sys.waitUntil(opts.topic, 300)
  509. end
  510. fd:close()
  511. end
  512. elseif opts.body then
  513. if type(opts.body) == "string" and #opts.body > 0 then
  514. socket.tx(netc, opts.body)
  515. write_counter = write_counter + #opts.body
  516. elseif type(opts.body) == "userdata" then
  517. write_counter = write_counter + opts.body:used()
  518. if opts.body:used() < 4*1024 then
  519. socket.tx(netc, opts.body)
  520. else
  521. local offset = 0
  522. local tmpbuff = opts.body
  523. local tsize = tmpbuff:used()
  524. while offset < tsize do
  525. opts.log(TAG, "body(zbuff)分段写入", offset, tsize)
  526. if tsize - offset > 4096 then
  527. socket.tx(netc, tmpbuff:toStr(offset, 4096))
  528. offset = offset + 4096
  529. sys.waitUntil(opts.topic, 300)
  530. else
  531. socket.tx(netc, tmpbuff:toStr(offset, tsize - offset))
  532. break
  533. end
  534. end
  535. end
  536. end
  537. end
  538. -- log.info("写入长度", "期望", opts.body_len, "实际", write_counter)
  539. -- log.info("hex", rbody)
  540. -- 处理响应信息
  541. while not opts.is_closed and opts.timeout > 0 do
  542. log.info(TAG, "等待服务器完成响应")
  543. sys.waitUntil(opts.topic, 1000)
  544. opts.timeout = opts.timeout - 1
  545. end
  546. log.info(TAG, "服务器已完成响应,开始解析响应")
  547. resp_parse(opts)
  548. -- log.info("执行完成", "返回结果")
  549. end
  550. --[[
  551. 执行HTTP请求
  552. @api httpplus.request(opts)
  553. @table 请求参数,是一个table,最起码得有url属性
  554. @return int 响应码,服务器返回的状态码>=100, 若本地检测到错误,会返回<0的值
  555. @return 服务器正常响应时返回结果, 否则是错误信息或者nil
  556. @usage
  557. -- 请求参数介绍
  558. local opts = {
  559. url = "https://httpbin.air32.cn/abc", -- 必选, 目标URL
  560. method = "POST", -- 可选,默认GET, 如果有body,files,forms参数,会设置成POST
  561. headers = {}, -- 可选,自定义的额外header
  562. files = {}, -- 可选,键值对的形式,文件上传,若存在本参数,会强制以multipart/form-data形式上传
  563. forms = {}, -- 可选,键值对的形式,表单参数,若存在本参数,如果不存在files,按application/x-www-form-urlencoded上传
  564. body = "abc=123",-- 可选,自定义body参数, 字符串/zbuff/table均可, 但不能与files和forms同时存在
  565. debug = false, -- 可选,打开调试日志,默认false
  566. try_ipv6 = false, -- 可选,是否优先尝试ipv6地址,默认是false
  567. adapter = nil, -- 可选,网络适配器编号, 默认是自动选
  568. timeout = 30, -- 可选,读取服务器响应的超时时间,单位秒,默认30
  569. bodyfile = "xxx", -- 可选,直接把文件内容作为body上传, 优先级高于body参数
  570. upload_buff = zbuff.create(1024*64) -- 可选,上传时使用的缓冲区,默认会根据型号创建一个buff
  571. }
  572. local code, resp = httpplus.request({url="https://httpbin.air32.cn/get"})
  573. log.info("http", code)
  574. -- 返回值resp的说明
  575. -- 情况1, code >= 100 时, resp会是个table, 包含2个元素
  576. if code >= 100 then
  577. -- headers, 是个table
  578. log.info("http", "headers", json.encode(resp.headers))
  579. -- body, 是个zbuff
  580. -- 通过query函数可以转为lua的string
  581. log.info("http", "headers", resp.body:query())
  582. -- 也可以通过uart.tx等支持zbuff的函数转发出去
  583. -- uart.tx(1, resp.body)
  584. end
  585. ]]
  586. function httpplus.request(opts)
  587. -- 参数解析
  588. local ret = http_opts_parse(opts)
  589. if ret then
  590. return ret
  591. end
  592. -- 执行请求
  593. local ret, msg = pcall(http_exec, opts)
  594. if opts.netc then
  595. -- 清理连接
  596. if not opts.is_closed then
  597. socket.close(opts.netc)
  598. end
  599. socket.release(opts.netc)
  600. opts.netc = nil
  601. end
  602. -- 处理响应或错误
  603. if not ret then
  604. log.error(TAG, msg)
  605. return -199, msg
  606. end
  607. return opts.resp_code, opts.resp
  608. end
  609. return httpplus