lua 发送http请求

16 篇文章 0 订阅

  lua发送http请求,luajit默认没有http.lua库,需要下载并存放到luajit对应目录。

一、下载http.lua和http_headers.lua库

参考:https://www.zixuephp.net/article-448.html

bash

  1. location = /testscript{
  2.     default_type text/plain;
  3.     content_by_lua_file html/luafile/test.lua;
  4. }
 

bash

  1. vim test.lua
  2. local zhttp = require "resty.http"

        1.运行后查看nginx错误日志,会提示没有http.lua文件:

 

        2.下载http.lua和http_headers.lua库

            下载页面:https://github.com/pintsized/lua-resty-http

            直接下载:http_headers.lua-http.lua.rar

            下载好后放入对应目录,这里的目录是:

 

bash

  1. [root@zixuephp resty]# pwd
  2. /usr/local/LuaJIT/share/luajit-2.0.5/resty
  3. git clone https://github.com/pintsized/lua-resty-http.git

 

 

    重启nginx。

二、lua发送http请求代码

    1.get请求

 

bash

  1. local zhttp = require "resty.http"
  2. local function http_post_client(url, timeout)
  3.         local httpc = zhttp.new()
  4.  
  5.         timeout = timeout or 30000
  6.         httpc:set_timeout(timeout)
  7.  
  8.         local res, err_ = httpc:request_uri(url, {
  9.                 method = "GET",
  10.                 headers = {
  11.                     ["Content-Type"] = "application/x-www-form-urlencoded",
  12.                 }
  13.         })
  14.         httpc:set_keepalive(5000, 100)
  15.         --httpc:close()
  16.         return res, err_
  17. end

    2.post请求

 

bash

  1. local zhttp = require "resty.http"
  2. local function http_post_client(url,body,timeout)
  3.         local httpc = zhttp.new()
  4.  
  5.         timeout = timeout or 30000
  6.         httpc:set_timeout(timeout)
  7.  
  8.         local res, err_ = httpc:request_uri(url, {
  9.                 method = "POST",
  10.                 body = body,
  11.                 headers = {
  12.                     ["Content-Type"] = "application/x-www-form-urlencoded",
  13.                 }
  14.         })
  15.         httpc:set_keepalive(5000, 100)
  16.          httpc:close()
  17.         if not res then 
  18.             return nil, err_ 
  19.          else if res.status == 200 then 
  20.              return res.body, err_ 
  21.          else 
  22.              return nil, err_ end 
  23.          end
  24.  
  25. end
 

bash

  1. --get
  2. local resp, err = http_post_client("http://zixuephp.net/index.html?name=test",3000)
  3. --post
  4. local body = {"name" = "test"}
  5. local resp, err = http_post_client("http://zixuephp.net/index.html?name=test",body,3000)
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值