引用相关文件
#include "network\HttpRequest.h"
#include "network\HttpClient.h"
#include "network\HttpResponse.h"
using namespace cocos2d::network;
xxx.h文件:
void complete(HttpClient *client,HttpResponse *response);
xxx.cpp文件:
//一:get请求 //创建request auto request = new HttpRequest(); request->setUrl("http://httpbin.org/ip"); request->setTag("type get"); request->setRequestType(HttpRequest::Type::GET); char data[50] = "data"; request->setRequestData(data,strlen(data));//请求的数据,数据的长度 request->setResponseCallback(CC_CALLBACK_2(TestHttp::complete,this)); //创建httpclinet对象 auto client = HttpClient::getInstance(); client->setTimeoutForConnect(60);//请求连接超时时间 client->setTimeoutForRead(100);//请求读写超时时间 client->send(request); request->release(); //二:post请求 auto postReq = new HttpRequest(); postReq->setTag("type post"); postReq->setUrl("http://httpbin.org/post"); postReq->setRequestType(HttpRequest::Type::POST); //设置请求头信息 std::vector<std::string> header; header.push_back("Content-Type:application/json;charset=utf-8"); postReq->setHeaders(header); //设置请求数据 const char* reqData = "controller=cocos2d&action=testHttpPost"; postReq->setRequestData(reqData,strlen(reqData));//请求的数据,数据的长度 postReq->setResponseCallback(CC_CALLBACK_2(TestHttp::complete,this)); auto client2 = HttpClient::getInstance(); //client2->send(postReq); //在请求时,会创建一个请求队列,sendImmediate会把改请求放到队列的前面,优先执行(此处先执行post完了后执行get)。 client2->sendImmediate(postReq); postReq->release();
void TestHttp::complete(HttpClient *client,HttpResponse *response) { //1.请求标识 log("request tag is:%s",response->getHttpRequest()->getTag()); //2.响应码 log("response code is:%d",response->getResponseCode()); //3.判断是否响应成功(很人性化) if(response->isSucceed()){ /*std::vector<char> * data = response->getResponseData(); log("response data is:"); for (int i = 0; i < data->size(); i++) { log("%c",(*data)[i]); }*/ //4.获取返回的数据(字符数组) std::vector<char> * data = response->getResponseData(); //创建一个标准的字符串流 std::stringstream oss; for (int i = 0; i < data->size(); i++) { oss<<(*data)[i];//字符数组data 输出到 字符串流oss } std::string str = oss.str();//字符串流转化为字符串 log("response data is:%s",str.c_str()); }else{ //获取返回的错误的信息 log("error msg is:%s",response->getErrorBuffer()); } }