cocos2dx 3.x 网络请求及json 解析

Cocos2dx 自带网络请求类 HttpRequest, 支持 get,post 请求,支持即时发送请求或者将请求放到发送队列中。json 解析使用第三方的 nlohmann json 库。

#include "cocos2d.h"
#include "network/HttpClient.h"
using namespace cocos2d::network;

Post 请求:

void HttpClientScene::post(){
    HttpRequest* request = new HttpRequest();
    request->setUrl("http://httpbin.org/post");
    request->setRequestType(HttpRequest::Type::POST);
    request->setResponseCallback(CC_CALLBACK_2(HttpClientScene::onHttpRequestCompleted,this));
    char* postData = "visitor=cocos2d&TestSuite=Extensions Test/NetworkTest";
    request->setRequestData(postData, strlen(postData));
    HttpClient::getInstance()->sendImmediate(request);
    request->release();
}

Get 请求:

void HttpClientScene::get(){
    HttpRequest* request = new HttpRequest();
    request->setUrl("http://httpbin.org/ip");
    request->setRequestType(HttpRequest::Type::GET);
    request->setResponseCallback(CC_CALLBACK_2(HttpClientScene::onHttpRequestCompleted, this));
    HttpClient::getInstance()->sendImmediate(request);
    request->release();
}
void HttpClientScene::onHttpRequestCompleted(HttpClient * sender,HttpResponse *response){
    if(response->isSucceed()){
        auto data = response->getResponseData();
    }
}

 

nlohmann json : 

1)先下载json.hpp, 并导入Android Studio

2)  引用 json.hpp, 并使用

#include "json.hpp"
void JsonScene::post(){
    HttpRequest *request = new HttpRequest();
    request->setRequestType(HttpRequest::Type::POST);
    request->setUrl("http://47.88.58.164:10005/horoscope/today");
    std::vector headers;
    headers.push_back("Content-Type: application/json; charset=utf-8");
    request->setHeaders(headers);

    nlohmann::json json;
    json["app"] = "com.horoscopetest.test.ios";
    json["ts"] = "1557479517";
    json["data"]["cid"] = 1;
    json["udid"] = "d36e2bf1e3ee5d5acfd6453932ff4208";
    json["version"] ="2410";
    std::string jsonString = json.dump();
    const char* postData = jsonString.c_str();
    request->setRequestData(postData,strlen(postData));
    request->setResponseCallback(CC_CALLBACK_2(JsonScene::onHttpRequestCompleted,this));
    HttpClient::getInstance()->sendImmediate(request);
    request->release();
}
void JsonScene::onHttpRequestCompleted(HttpClient * sender,HttpResponse *response){
    if(response->isSucceed()){
        std::vector *buffer = response->getResponseData();
        std::stringstream oss;
        for (int i = 0; i < buffer->size() ; ++i) {
            oss<< (*buffer)[i];
        }
        std::string temp = oss.str();
        parseForProperty(temp);
    }
}
void JsonScene::parseForProperty(std::string temp) {
    if(temp.size() >0){
        auto j = nlohmann::json::parse(temp.c_str());
        career = j["data"]["horoscope"]["career"].get();
        careerMatch = j["data"]["horoscope"]["careerMatch"].get();
        date = j["data"]["horoscope"]["date"].get();
    }
}

 

你可能感兴趣的:(cocso2dx,3.x版本学习)