Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Http for network communication


May 21, 2021 CrossApp



CrossApp encapsulates http's network framework for us, and its files are httpClient, HttpRequest, and HttpResponse under the CrossApp engine pack's .extensions.network file.

There are three classes that need to be involved in an http interaction:

HttpRequest is used to describe a request.

HttpResponse is used to describe the response to the request.

HttpClient is a single-case pattern class that is responsible for pushing the received HttpRequest object into the sending queue and sending a sedum-driven worker who encapsulates the received data into a HttpResponse object push receive queue and enables scheduling to deliver the data.


Reference header file:

#include "CrossAppExt.h"

Request

/**
编译到Android平台之后注意添加联网权限
**/
//创建request对象,这里new出来的对象不能使用autorelease(),原因后述  
CAHttpRequest* request = new CAHttpRequest();
 
//设置URL
request->setUrl("www.9maio.com");
 
//设置请求类型kHttpGet、kHttpPost、KHttpPostFile、kHttpPut、kHttpDelete、kHttpUnkown
request->setRequestType(CAHttpRequest::kHttpGet);
 
//这是回调对象和回调函数  
request->setResponseCallback(this, httpresponse_selector(FirstViewController::requestresult));
 
//使用CCHttpClient共享实例来发送request
CAHttpClient::getInstance()->send(request);
 
//调用release() 
request->release();

Receive

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);
    }
}