W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
CrossApp為我們封裝了http的網(wǎng)絡(luò)框架,其文件在CrossApp引擎包的\extensions\network文件下的 HttpClient、HttpRequest 、HttpResponse。
進(jìn)行一次http交互,需要涉及的有三個(gè)類:
HttpRequest 用來描述一個(gè)請(qǐng)求。
HttpResponse 用來描述對(duì)應(yīng)請(qǐng)求的響應(yīng)。
HttpClient是一個(gè)單例模式的類,它的職責(zé)就是負(fù)責(zé)將收到的HttpRequest對(duì)象push到發(fā)送隊(duì)列中,并發(fā)送一個(gè)信號(hào)量驅(qū)動(dòng)工作線程工作,工作線程再將收到的數(shù)據(jù)封裝成一個(gè)HttpResponse對(duì)象push接收隊(duì)列,并啟用調(diào)度來派送數(shù)據(jù)。
引用頭文件:
#include "CrossAppExt.h"
請(qǐng)求
/**
編譯到Android平臺(tái)之后注意添加聯(lián)網(wǎng)權(quán)限
**/
//創(chuàng)建request對(duì)象,這里new出來的對(duì)象不能使用autorelease(),原因后述
CAHttpRequest* request = new CAHttpRequest();
//設(shè)置URL
request->setUrl("www.9maio.com");
//設(shè)置請(qǐng)求類型kHttpGet、kHttpPost、KHttpPostFile、kHttpPut、kHttpDelete、kHttpUnkown
request->setRequestType(CAHttpRequest::kHttpGet);
//這是回調(diào)對(duì)象和回調(diào)函數(shù)
request->setResponseCallback(this, httpresponse_selector(FirstViewController::requestresult));
//使用CCHttpClient共享實(shí)例來發(fā)送request
CAHttpClient::getInstance()->send(request);
//調(diào)用release()
request->release();
接收
void FirstViewController::requestresult(CAHttpClient* clinet, CAHttpResponse* response)
{
if (!response->isSucceed())
{
return;
}
//獲取返回代碼,比如200、404等
int statusCode = response->getResponseCode();
if (statusCode == 200)
{
std::string responseRes = "";
std::vector<char> *buffer = response->getResponseData();
for (unsigned int i = 0; i < buffer->size(); i++)
{
responseRes += (*buffer)[i];
}
//查找字符“官方特約”
string::size_type idx = responseRes.find(UTF8("官方特約"));
if (idx == -1)
{
//為找到字符
CCLog(" Not Found");
return;
}
string temp = responseRes.substr(idx, 30);
string num = temp.substr(temp.find(UTF8(":")) + 3, temp.find("<") - temp.find(UTF8(":")) - 3);
CCLog("temp:%s",temp.c_str());
}
else
{
//打印返回代碼
CCLog("statusCode:%d", statusCode);
}
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: