cocos2d-x 3.1.1 学习笔记[11] http请求 + json解析


//http须要引入的头文件和命名空间
#include <network/HttpClient.h>
using namespace network;

//json须要引入的头文件
#include <json/document.h>

    //然后声名两个函数
    void http();//用于运行http请求
    void onHttpRequestCompleted(cocos2d::network::HttpClient *sender, cocos2d::network::HttpResponse *response);// http请求的回调

void Nice::http()
{
    //创建一个get请求
    HttpRequest* request = new HttpRequest();
    request->setUrl("http://api.map.baidu.com/telematics/v3/weather?location=%E5%8C%97%E4%BA%AC&output=json&ak=Gk0Bbh9H4iREjesugyEqySN7");
    request->setRequestType(HttpRequest::Type::GET);
    request->setResponseCallback(CC_CALLBACK_2(Nice::onHttpRequestCompleted, this));
    request->setTag("json");
    HttpClient::getInstance()->send(request);
    request->release();
    
    //创建一个post请求
    HttpRequest* request_post = new HttpRequest();
    request_post->setUrl("http://httpbin.org/post");
    request_post->setRequestType(HttpRequest::Type::POST);
    std::vector<std::string> headers;
    headers.push_back("Content-Type: application/json; charset=utf-8");
    request_post->setHeaders(headers);
    request_post->setResponseCallback(CC_CALLBACK_2(Nice::onHttpRequestCompleted, this));
    //post数据
    const char* postData = "visitor=cocos2d&TestSuite=Extensions Test/NetworkTest";
    request_post->setRequestData(postData, strlen(postData));
    request_post->setTag("POST test2");
    HttpClient::getInstance()->send(request_post);
    request_post->release();
}

void Nice::onHttpRequestCompleted(cocos2d::network::HttpClient *sender, cocos2d::network::HttpResponse *response)
{
    if (!response) {
        return;
        
    }
    
    if (0 != strlen(response->getHttpRequest()->getTag())) {
        log("%s completed",response->getHttpRequest()->getTag());
    }
    
    long statusCode = response->getResponseCode();
    char statusString[64] = {};
    
    sprintf(statusString, "HTTP Status Code: %ld, tag = %s",statusCode,response->getHttpRequest()->getTag());
    log("response code: %ld",statusCode);
    
    if (!response->isSucceed()) {
        log("response failed");
        log("error buffer: %s",response->getErrorBuffer());
        return;
        
    }
    
    std::vector<char>* buffer = response->getResponseData();
    printf("Http Test, dump data: ");
    for (unsigned int i = 0 ; i < buffer->size();i++) {
        printf("%c",(*buffer)[i]);
    }
    
    //将std::vector(char)* 转换成 std::string的两种方法
    std::string backStr = std::string(&(*buffer->begin()), buffer->size());
    std::string anotherStr;
    anotherStr.insert(anotherStr.begin(), buffer->begin(), buffer->end());
    printf("%s
", backStr.c_str());
    printf("%s
", anotherStr.c_str());
    printf("
");
    
    
    if (strcmp(response->getHttpRequest()->getTag(), "json") == 0) {
        rapidjson::Document doc;
        doc.Parse<0>(backStr.c_str());
        const rapidjson::Value& v = doc["status"];
        printf("status is : %s",v.GetString());
        const rapidjson::Value& dir = doc["results"];
        if (dir.IsArray()) {
            unsigned int i = 0;
            const rapidjson::Value& city = dir[i]["currentCity"];
            log("city is %s", city.GetString());
            //多层測试
            const rapidjson::Value& title = doc["results"][(unsigned int)0]["index"][(unsigned int)2]["title"];
            log("the title is %s", title.GetString());
        }
    }
    
    
}











原文地址:https://www.cnblogs.com/yxysuanfa/p/6800412.html