HTTP 模块(仅支持iOS)

函数名称:http.get、http.post、http.header、http.build_request

函数功能:发送 httpGET 请求、发送 httpPOST 请求

函数方法

status_resp, headers_resp, body_resp = http.get("http://82flex.com", 5, headers_send) status_resp, headers_resp, body_resp = http.post("http://dev.touchsprite.com/site/login", 3, headers_send, post_escaped)

参数 类型 必填 说明
url string 请求 URL
time_out number 超时时间(秒)
headers_send string 请求头部 json
post_escaped string 请求内容
返回值 类型 说明
status_resp number HTTP 状态码
headers_resp string 响应头部 json
body_resp string 响应内容

函数用例

--采用 cjson 构造请求头部 json
local sz = require("sz")
local cjson = sz.json
local http = sz.i82.http
headers = {}
headers['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36'
headers['Referer'] = 'http://www.82flex.com'
headers_send = cjson.encode(headers)
dialog(headers_send,0)
status_resp, headers_resp, body_resp = http.get("http://82flex.com",5,headers_send)
if status_resp ~= nil then
    dialog(status_resp,0)
    dialog(headers_resp,0)
    if status_resp == 200 then
        dialog(string.len(body_resp),0)
    end
end
--采用 cjson 构造请求头部 json
local sz = require("sz")
local cjson = sz.json
local http = sz.i82.http
headers = {}
headers['User-Agent'] = 'Mozilla/5.0 (Macintosh;Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/40.0.2214.111 Safari/537.36'
headers['Referer'] = 'http://dev.touchsprite.com/site/login'
headers_send = cjson.encode(headers)
dialog(headers_send,0)
--采用 cjson 构造请求内容,并进行 escape
post = {}
post['username'] = "i_82"
post['password'] = '12345678'
post['text'] = '触动精灵'
post_send = cjson.encode(post)
dialog(post_send,0)
post_escaped = http.build_request(post_send)
dialog(post_escaped,0)
status_resp, headers_resp, body_resp = http.post("http://dev.touchsprite.com/site/login",3,headers_send, post_escaped)
dialog(status_resp,0)
dialog(headers_resp,0)
if status_resp ~= nil then
    dialog(status_resp,0)
    dialog(headers_resp,0)
    if status_resp == 200 then
        dialog(string.len(body_resp),0)
    end
    --获取响应信息头部指定字段
    --方法一
    server = http.header(headers_resp, "Server")
    dialog(server,0)
    --方法二
    servers = cjson.decode(headers_resp)
    dialog(servers["Server"],0)
end
--用 http.get 实现下载文件功能
local sz = require("sz")
local cjson = sz.json
local http = sz.i82.http

function downFile(url, path)
    status, headers, body = http.get(url)
    if status == 200 then
        file = io.open(path, "wb")
        if file then
            file:write(body)
            file:close()
            return status;
        else
            return -1;
        end
    else
        return status;
    end
end
downFile("http://www.touchsprite.com/img/headline-new.png", "/User/Media/TouchSprite/res/1.png")
Copyright 北京帮你玩科技有限公司 2024 all right reserved,powered by Gitbook该文章修订时间: 2024-10-08 11:38:05

results matching ""

    No results matching ""