cocos2d-x-3.16使用HttpRequest请求

cocos2dx实现网络通信
使用cocos2dx-3.16 编辑器Xcode9.2

头文件

//
//  LayerStart.hpp
//  CardGame
//
//  Created by Apple on 2018/3/2.
//

#ifndef LayerStart_h
#define LayerStart_h

#include "cocos2d.h"
#include "network/HttpClient.h"

USING_NS_CC;
using namespace cocos2d::network;


class LayerStart : public cocos2d::Layer
{
public:
    static cocos2d::Scene* createScene();

    virtual bool init();

    // a selector callback
    void menuCloseCallback(cocos2d::Ref* pSender);

    // implement the "static create()" method manually
    CREATE_FUNC(LayerStart);

    // 请求方法
    void postHttpRequest();
    // 请求完成的回调方法
    void onHttpRequestCompleted(HttpClient *sender, HttpResponse *response);

};

#endif /* LayerStart_h */

CPP文件

//
//  LayerStart.cpp
//  CardGame
//
//  Created by Apple on 2018/3/2.
//
#include "LayerStart.h"
#include "LayerGame.h"
Scene* LayerStart::createScene()
{
    Scene *secen = Scene::create();
    LayerStart *start = LayerStart::create();
    secen->addChild(start);
    return secen;
}

// on "init" you need to initialize your instance
bool LayerStart::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }
    return true;

}

void LayerStart::postHttpRequest()
{
    HttpRequest* request = new HttpRequest();
    request->setUrl("http://127.0.0.1:8080/user/login.action");
    request->setRequestType(HttpRequest::Type::POST);
    request->setResponseCallback(CC_CALLBACK_2(LayerStart::onHttpRequestCompleted,this));

    // write the post data
    const char* postData = "visitor=cocos2d&TestSuite=Extensions Test/NetworkTest";
    request->setRequestData(postData, strlen(postData));
    request->setTag("POST test");
    cocos2d::network::HttpClient::getInstance()->send(request);
    request->release();
}

void LayerStart::onHttpRequestCompleted(HttpClient *sender, HttpResponse *response)
{
    if (!response)
    {
        return;
    }

    // You can get original request type from: response->request->reqType
    if (0 != strlen(response->getHttpRequest()->getTag()))
    {
        log("%s completed", response->getHttpRequest()->getTag());
    }
    int statusCode = response->getResponseCode();
    char statusString[64] = {};
    sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag());
    log("response code: %d", statusCode);
    if (!response->isSucceed())
    {
        log("response failed");
        log("error buffer: %s", response->getErrorBuffer());
        return;
    }
    // dump data
    std::vector<char> *buffer = response->getResponseData();
    printf("Http Test, dump data: ");
    for (unsigned int i = 0; i < buffer->size(); i++)
    {
        printf("%c", (*buffer)[i]);
    }
    printf("\n");
}

解析CPP中onHttpRequestCompleted方法中的buffer即可得到接口返回的数据

你可能感兴趣的:(cocos2dx)