转载请注明出处:https://blog.csdn.net/qq_28779503
Cocos2d-x封装了3个类来处理HTTP请求:
HttpRequest,HttpClient和HttpResponse.
使用HttpRequest,HttpClient和HttpResponse这3个类进行Http进行请求时,需要遵循一定流程
请求过程:
1.创建HttpRequest的实例。
2.设置请求方式,Get、Post等。(千万不要以为只有get和post方式哦,这是一般新手以为的,只是其他请求方式我们平时用到的很少)
3.设置请求地址和发送的数据(如果没有发送的数据,可不设置发送数据)。
4.设置响应回调函数,在回调函数中处理获取的数据。
5.创建HttpClient实例,发送请求。
6.释放请求连接。
使用Cocos2d封装的HttpRequest设置请求信息
HttpRequest:
是一种数据类型,它提供了一些方法用来定义或获取HTTP请求的参数,
常用方法包括下面几种:
设置请求连接
void setUrl(const char * url);
设置请求类型
void setRequestType(Type type);
这里的Type是Cocos2d-x定义的一个枚举类型,包括5种类型。
class CC_DLL HttpRequest : public Ref
{
public:
/**
* The HttpRequest type enum used in the HttpRequest::setRequestType.
*/
enum class Type
{
GET,
POST,
PUT,
DELETE,
UNKNOWN,
};
...
}
设置回调函数:
void setResponseCallback(Ref* pTarget,SEL_HttpResponse pSelector);
设置请求的数据,参数buffer是提交的数据,len是请求数据的长度(使用发送数据的实际长度):
void setRequestData(const char* buffer,unsigned int len);
auto request = new HttpRequest();
//设置请求网址
request->setUrl("请填写你需要请求的网址");
//设置请求类型
request->setRequestType(HttpRequest::Type::GET);
//设置请求的数据
char data[50] = "data";
request->setRequestData(data,strlen(data));
HttpClient实现表情包下载与显示:
require("json")
function MainScene:onCreate()
local selfRoot = self:getResourceNode()
--利用CocosStudio进行布局
local TextBiaoQing = selfRoot:getChildByName("KW_TEXTFIELD_BIAO_QING")
local BtnBiaoQing = selfRoot:getChildByName("KW_BTN_BIAO_QING")
local image = ccui.ImageView:create()
image:loadTexture("myTest.png",0)
image:setPosition(300,450)
selfRoot:addChild(image)
local index = 1
local function onClickBiaoQing()
local BiaoQingDescStr = TextBiaoQing:getString() --获取输入框中文字(所要请求的表情包)
--以"斗图网"为例:https://www.doutula.com/
--请求地址:https://www.doutula.com/api/search?keyword=金馆长&mime=0&page=2
--参数说明:keyword => 关键词, page => 分页(最大支持50页), mime => 图片类型(0: 所有, 1: 动图, 2: 静图, --mime方式过虑有漏网的,使用的可以自行过虑一下。)
--请求方法:GET或POST
--先通过网站提过的API接口获取相应数据(数据中可能包含表情包描述及图片RUL等)
local xhr = cc.XMLHttpRequest:new()
xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_STRING
local req = "https://www.doutula.com/api/search?keyword=" .. BiaoQingDescStr .. "&mime=0&page=1"
xhr:open("GET",req)
local fullFileNameUrl = ""
local function onReadyStateChange()
if xhr.readyState == 4 and (xhr.status >= 200 and xhr.status < 207) then --请求状态已完并且请求已成功
local statusString = "Http Status Code:"..xhr.statusText
local response = xhr.response --获得返回的内容
--获取到的是json字符串,但是该字符串不符合lua中封装的json文件的解析规则,会报错。
--去掉"\\"字符串依旧正常,符合Lua语法规则,之后便可以正常解析
local response = string.gsub(response,"\\","")
local output = json.decode(response) --解析json数据
index = index + 1
fullFileNameUrl = output["data"]["list"][index]["image_url"] --取图片的URL地址
--以下是通过图片的URL地址,请求该图片数据并保存到本地,然后进行贴图显示(图片也是数据构成的,可以用notpad++打开)
local xhr = cc.XMLHttpRequest:new()
--每次下载的图片都需要索引+1,然后image再去loadTexture该图片,如果图片名字不变,image所loadTexture的是缓存中的Texture,不会更新
xhr._urlFileName = "myTest" .. index .. ".jpg"
xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_STRING
xhr:open("GET", fullFileNameUrl)
local function onDownloadImage()
if xhr.readyState == 4 and (xhr.status >= 200 and xhr.status < 207) then
local fileData = xhr.response
--这里要把下载下来的文件放到预设的"res"文件夹下,否则loadTexture会找不到图片
local fullFileName = cc.FileUtils:getInstance():getWritablePath() .."res" .. "\\" .. xhr._urlFileName
local file = io.open(fullFileName,"wb")
file:write(fileData) --这里将图片数据写入该文件,数据写入完成之后便是一张图片了
file:close()
image:loadTexture(xhr._urlFileName,0) --图片贴图,显示表情包
end
end
xhr:registerScriptHandler(onDownloadImage)
xhr:send()
end
end
xhr:registerScriptHandler(onReadyStateChange)
xhr:send()
end
BtnBiaoQing:addClickEventListener(onClickBiaoQing)
end
效果如下图,输入表情包名称,点击“笑脸”按钮便可以获取并显示表情包。