• lua 发送http请求


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

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

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

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

     
    bash

    vim test.lua
    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

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

        重启nginx。

    二、lua发送http请求代码

        1.get请求


     
    bash

    local zhttp = require "resty.http"
    local function http_post_client(url, timeout)
            local httpc = zhttp.new()
     
            timeout = timeout or 30000
            httpc:set_timeout(timeout)
     
            local res, err_ = httpc:request_uri(url, {
                    method = "GET",
                    headers = {
                        ["Content-Type"] = "application/x-www-form-urlencoded",
                    }
            })
            httpc:set_keepalive(5000, 100)
            --httpc:close()
            return res, err_
    end
        2.post请求


     
    bash

    local zhttp = require "resty.http"
    local function http_post_client(url,body,timeout)
            local httpc = zhttp.new()
     
            timeout = timeout or 30000
            httpc:set_timeout(timeout)
     
            local res, err_ = httpc:request_uri(url, {
                    method = "POST",
                    body = body,
                    headers = {
                        ["Content-Type"] = "application/x-www-form-urlencoded",
                    }
            })
            httpc:set_keepalive(5000, 100)
             httpc:close()
            if not res then 
                return nil, err_ 
             else if res.status == 200 then 
                 return res.body, err_ 
             else 
                 return nil, err_ end 
             end
     
    end

     
    bash

    --get
    local resp, err = http_post_client("http://zixuephp.net/index.html?name=test",3000)
    --post
    local body = {"name" = "test"}
    local resp, err = http_post_client("http://zixuephp.net/index.html?name=test",body,3000)

  • 相关阅读:
    MySQL查询缓存
    MySQL复制相关参数详解
    MySQL复制机制
    MySQL数据库的多表查询操作
    MySQL数据库单表查询基本操作及DML语句
    Hadoop大数据系列汇总
    MySQL数据库之日志功能详解
    MySQL数据库扫盲
    MySQL数据库之数据类型及基本使用详解
    MySQL数据库之日志管理
  • 原文地址:https://www.cnblogs.com/xiami2046/p/12605193.html
Copyright © 2020-2023  润新知