异步http请求
首先包含头文件
#include "network/HttpRequest.h"
#include "network/HttpClient.h"
using namespace network;
代码部分:
//GET方式
void HelloWorld::HttpGet(){
HttpRequest* request = new HttpRequest();
request -> setUrl("http://192.168.0.0:8080/service/userlogin?username=test12&userpassword=123456");
request -> setRequestType(cocos2d::network::HttpRequest::Type::GET);
request -> setResponseCallback(CC_CALLBACK_2(HelloWorld::Response, this));
request -> setTag("get");
HttpClient::getInstance() -> send(request);
request -> release();
}
//POST方式
void HelloWorld::HttpPost(){
char data[50];
sprintf(data, "username=test12&userpassword=123456");//字符串拷贝
HttpRequest* request = new HttpRequest();
request -> setUrl("http://192.168.0.0:8080/service/userlogin");
request -> setRequestType(cocos2d::network::HttpRequest::Type::POST);
request -> setRequestData(data, std::strlen(data));
request -> setResponseCallback(CC_CALLBACK_2(HelloWorld::Response, this));
request -> setTag("post");
HttpClient::getInstance() -> send(request);
request -> release();
}
void HelloWorld::Response(HttpClient* client, HttpResponse* response){
if (!response) {
return;
}
log("%s",response -> getHttpRequest() -> getTag());
log("%ld",response -> getResponseCode());//获得返回状态
std::vector<char>* buffer = response -> getResponseData();
__String* str = __String::create("");
for (int i = 0; i < buffer->size(); i++) {
str -> appendWithFormat("%c",(*buffer)[i]);
}
log("%s",str -> getCString());
//...接下来的操作
}
参考我之前的两篇教程进行接下去的操作
http://blog.csdn.net/tiantangyouzui/article/details/50902672 json的操作
http://blog.csdn.net/tiantangyouzui/article/details/50902696 xml的操作