HomeServer/Server/Lib/Http/HttpClient.lua
2024-11-20 15:41:37 +08:00

84 lines
2.8 KiB
Lua
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

local httpc = require "http.httpc"
local dns = require "skynet.dns"
local skynet = require "skynet"
local oo = require "Class"
local log = require "Log"
local HttpClient = oo.class()
function HttpClient:Init()
end
-- GET 请求 参数说明url域名如 www.baidu.com不包含https://,param:域名后面的路径,如 /test/test.html,protocol:协议(https或者http)默认http
function HttpClient:Get( url , param ,protocol )
httpc.timeout = 300 -- set timeout 1 second
protocol = protocol or "http"
local respheader = {}
local host = string.format("%s://%s", protocol,url)
log.info("Getting ", protocol , host..param)
local status, body = httpc.get(host, param, respheader)
log.info("Web Get返回信息", host..param,status,body)
return status,body
end
-- PostJson 请求 参数说明url域名如 www.baidu.com不包含https://,param:域名后面的路径,如 /test/test.html,form:请求参数哈希table类型,protocol:协议(https或者http)默认http
function HttpClient:Post( url ,param,form,protocol )
httpc.timeout = 300 -- set timeout 2 second
log.debug("POST "..url)
protocol = protocol or "http"
local respheader = {}
local host = string.format("%s://%s", protocol,url)
log.debug("Posting ".. host..param)
--log.info("Post data ", skynet.server.common:TableToString(form))
local status, body = httpc.post(host, param, form , respheader)
for k,v in pairs(respheader) do
print(k,v)
end
log.debug("Web Post返回信息", status,body)
return status,body
end
-- PostJson 请求 参数说明url域名如 www.baidu.com不包含https://,param:域名后面的路径,如 /test/test.html,jsonData:请求参数json格式,protocol:协议(https或者http)默认http
function HttpClient:PostJson( url ,param, jsonData ,protocol )
function Do( url ,param, jsonData ,protocol)
httpc.timeout = 200 -- set timeout 2 second
protocol = protocol or "http"
local respheader = {}
local host = string.format("%s://%s", protocol,url)
log.debug("PostJson ".. host..param)
--log.info("PostJson data ",jsonData)
local status, body = httpc.postJson(host, param, jsonData , respheader)
--for k,v in pairs(respheader) do
--print(k,v)
--end
log.debug("Web PostJson返回信息", status,body)
return status,body
end
local isSuc,status,body = pcall( Do, url ,param, jsonData ,protocol )
if not isSuc then
log.info("PostJson请求失败",url,status)
end
return status,body,isSuc
end
--[[
function Do( host, param, jsonData , respheader )
local status, body = httpc.postJson(host, param, jsonData , respheader)
for k,v in pairs(respheader) do
print(k,v)
end
end
local isSuc,err = pcall(Do, host, param, jsonData , respheader )
if not isSuc then
log.info("XXXXXXXXXXXXX",err)
end
log.info("返回信息", status,body)
]]
skynet.server.httpClient = HttpClient
return HttpClient