OpenResty默認沒有提供Http客戶端,需要使用第三方提供;當然我們可以通過ngx.location.capture 去方式實現,但它只能發送一個子請求。
第三方基本是以lua-resty-http為代表,這個類庫如果去訪問http和正規的https是沒有問題,也挺好用的,但如果訪問使用山寨證書的請求會出一些錯誤,比如:handshake failed,socket error等等之類的錯誤。對於種我的解決辦法是使用curl,可以很好解決這個問題,現在來看算是比較完美的。
具體代碼如下:
local curl = require("luacurl") local function postJson(url,postData,c) local result = { } if c == nil then c = curl.new() end c:setopt(curl.OPT_URL, url) c:setopt(curl.OPT_SSL_VERIFYHOST,0) c:setopt(curl.OPT_SSL_VERIFYPEER,false) c:setopt(curl.OPT_POST,true) c:setopt(curl.OPT_HTTPHEADER, "Content-Type: application/json") c:setopt(curl.OPT_POSTFIELDS, postData) c:setopt(curl.OPT_WRITEDATA, result) c:setopt(curl.OPT_WRITEFUNCTION, function(tab, buffer) table.insert(tab, buffer) return #buffer end) local ok = c:perform() return ok, table.concat(result) end local ok,html = postJson(serverUrl,data); if ok then ngx.say(html) end
