Cocos网络篇[3.2](2) ——HTTP连接
1
2
3
4
5
6
7
|
//
// 用GET获取表单数据,表单数据对任何人都是可见的
http: //www.abc.com/index.php?username=shahdza&password=123
// 用POST获取表单数据,表单数据则是不可见的
http: //www.abc.com.cn/index.php
//
|
1
2
3
4
|
//
#include "network/HttpClient.h"
using namespace network;
//
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
//
/**
*
HttpRequest 相关
**/
HttpRequest
{
// 请求方式
HttpRequest::Type::GET
HttpRequest::Type::POST
// 设置请求方式
void setRequestType(Type type);
// 设置访问服务器的资源URL
void setUrl( const char * url);
// 发送请求数据,用于POST方式
void setRequestData( const char * buffer, size_t len);
// 绑定请求的响应函数
void setResponseCallback( const ccHttpRequestCallback& callback);
// HttpResponse为服务器返回的响应信息
callback(HttpClient* sender, HttpResponse* response);
};
/**
*
HttpResponse 相关
**/
HttpResponse
{
// HTTP请求是否成功
bool isSucceed();
// 响应代码
long getResponseCode();
// 错误信息
const char * getErrorBuffer();
// 发送回来的响应数据信息
std::vector< char >* getResponseData();
};
/**
*
HttpClient 相关
**/
HttpClient
{
// 获取HttpClient单例
static HttpClient* getInstance();
static void destroyInstance();
// 发送HTTP请求
void send(HttpRequest* request);
// 设置连接超时时长
inline void setTimeoutForConnect( int value) {_timeoutForConnect = value;};
// 设置下载超时时长
inline void setTimeoutForRead( int value) {_timeoutForRead = value;};
};
//
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
//
// 发送HTTP请求
void HelloWorld::onHttpRequest(std::string type)
{
// 创建HTTP请求
HttpRequest* request = new HttpRequest();
if (type == "get" )
{
request->setRequestType(HttpRequest::Type::GET);
// url后面附加数据信息
request->setUrl( "http://httpbin.org/get?name=hello&pwd=world" );
}
else if (type == "post" )
{
request->setRequestType(HttpRequest::Type::POST);
request->setUrl( "http://httpbin.org/post" );
// 设置post发送请求的数据信息
std::string data = "hello world!" ;
request->setRequestData(data.c_str(), data.length());
}
// HTTP响应函数
request->setResponseCallback(CC_CALLBACK_2(HelloWorld::onHttpResponse, this ));
// 发送请求
HttpClient::getInstance()->send(request);
// 释放链接
request->release();
}
// HTTP响应请求函数
void HelloWorld::onHttpResponse(HttpClient* sender, HttpResponse* response)
{
// 没有收到响应
if (!response)
{
CCLOG( "no response" );
return ;
}
int statusCode = response->getResponseCode();
char statusString[64] = {};
sprintf (statusString, "HTTP Status Code: %d, tag = %s" , statusCode, response->getHttpRequest()->getTag());
CCLOG( "response code: %s" , statusString);
// 链接失败
if (!response->isSucceed())
{
CCLOG( "response failed" );
CCLOG( "error buffer: %s" , response->getErrorBuffer());
return ;
}
// 获取数据
std::vector< char >* v = response->getResponseData();
for ( int i = 0; i < v->size(); i++)
{
printf ( "%c" , v->at(i));
}
printf ( "\n" );
}
//
|