你是否遇到过url过长,既不利于ui展示也不利于生成二维码的情况?
额,既然长了,那就搞短一点!
短网址有以下优势:
- 短,美观;
- 生成的二维码比较简单,便于识别;
- 便于数据统计;
这里记录两个生成短网址的第三方API(免费)!
SOHU短网址
API:接口文档
准备:注册账号获取API key
TestDemo:
local TestDemo = class("TestDemo")
function TestDemo:ctor()
self:testSOHUShortLink()
end
-- SOHO短网址
function TestDemo:testSOHUShortLink()
local key = "YourKey"
local longURL = string.urlencode("https://www.baidu.com") -- 必须要对原始url进行UrlEncode
self:getSOHUShortLink(key, longURL, handler(self, self.shortLinkCallFunc))
end
function TestDemo:shortLinkCallFunc(shortURL)
print("shortURL->", shortURL)
end
function TestDemo:getSOHUShortLink(key, longURL, callFunc)
local xhr = cc.XMLHttpRequest:new()
xhr.timeout = 5
xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_STRING
local reqUrl = string.format("https://sohu.gg/api/?key=%s&url=%s", key, longURL)
xhr:open("GET", reqUrl)
local function httpCallback()
if xhr.readyState == 4 and xhr.status == 200 then
local response = xhr.response
if callFunc then
if response == "" then
callFunc(reqUrl)
else
callFunc(response)
end
end
end
xhr:unregisterScriptHandler()
end
xhr:registerScriptHandler(httpCallback)
xhr:send()
end
return TestDemo
ps:
- 必须要对原始url进行UrlEncode!
- 同一个url每次生成出来的短网址都是一样的!如果需要同一个url每次生成出来的短网址都不同,可以在原始url后面拼接一个时间戳!
- 生成的短网址永久有效,不会过期!
SuoLink
API:接口文档
准备:注册账号获取key
TestDemo:
local TestDemo = class("TestDemo")
function TestDemo:ctor()
self:testSLShortLink()
end
-- SuoLink短网址
function TestDemo:testSLShortLink()
local longURL = string.urlencode("https://www.baidu.com") -- 必须要对原始url进行UrlEncode
local key = "YourKey"
self:getSLShortLink(longURL, key, nil, handler(self, self.shortLinkCallFunc))
-- self:getSLShortLink(longURL, key, "2040-06-06", handler(self, self.shortLinkCallFunc))
end
function TestDemo:shortLinkCallFunc(shortURL)
print("shortURL->", shortURL)
end
function TestDemo:getSLShortLink(longURL, key, expireDate, callFunc)
local xhr = cc.XMLHttpRequest:new()
xhr.timeout = 5
xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_STRING
local reqUrl = ""
if expireDate and expireDate ~= "" then
reqUrl = string.format("http://api.suolink.cn/api.htm?url=%s&key=%s&expireDate=%s", longURL, key, expireDate)
else
reqUrl = string.format("http://api.suolink.cn/api.htm?url=%s&key=%s", longURL, key)
end
xhr:open("GET", reqUrl)
local function httpCallback()
if xhr.readyState == 4 and xhr.status == 200 then
local response = xhr.response
if callFunc then
if response == "" then
callFunc(reqUrl)
else
callFunc(response)
end
end
end
xhr:unregisterScriptHandler()
end
xhr:registerScriptHandler(httpCallback)
xhr:send()
end
return TestDemo
ps:
- 必须要对原始url进行UrlEncode!
- 同一个url每次生成出来的短网址都是不同的!
- 可以设置短网址的有效期,如果不设置就默认三个月的有效期,设置到2040年之后就默认为永久有效!短网址的有效期在后台可以修改!