HTTP 통신



h++)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#ifndef test396_hpp
#define test396_hpp
 
#include "cocos2d.h"
#include "network/HttpClient.h"
 
USING_NS_CC;
using namespace cocos2d::network;
 
 
class Test396 : public Layer
{
public:
    virtual bool init();
    static Scene* createScene();
    CREATE_FUNC(Test396);
    
    
    void onHttpRequestCompleted(HttpClient *sender, HttpResponse *response);
};
 
#endif
cs



c++)

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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include "test396.hpp"
 
 
USING_NS_CC;
 
 
Scene* Test396::createScene()
{
    auto scene = Scene::create();
    
    auto layer = Test396::create();
    scene->addChild(layer);
    
    
    return scene;
}
 
 
bool Test396::init()
{
    if ( !Layer::init())
    {
        return false;
    }
    
    
    //HttpRequest 객체 생성
    HttpRequest *request = new HttpRequest();
    
    //URL 지정
    request->setUrl("https://httpbin.org/ip");
    
    //통식방식 지정
    request->setRequestType(HttpRequest::Type::GET);
    
    //Response Selector 지정
    request->setResponseCallback(this, httpresponse_selector(Test396::onHttpRequestCompleted));
    //POST 방식의 데이터 보내기
    //const char *postData = "visitor=cocos2d";
    //request->setRequestData(postData, strlen(postData));
    
    request->setTag("GET TAG");    //태그
    
    //전송
    HttpClient::getInstance()->send(request);
 
    //릴리즈
    request->release();
    
    
    return true;
}
 
 
//요청 결과받기
void Test396::onHttpRequestCompleted(HttpClient *sender, HttpResponse *response){
    if(!response) return;
    
    //태그 출력
    if(0!=strlen(response->getHttpRequest()->getTag())){
        CCLOG("%s completed", response->getHttpRequest()->getTag());
    }
 
    //HTTP 상태코드
    long statusCode = response->getResponseCode();
    CCLOG("response code : %ld", statusCode);
 
    //통신 실패시
    if(!response->isSucceed()){
        CCLOG("response failed");
        CCLOG("error buffer : %s", response->getErrorBuffer());
        return;
    }
 
    //통신 성공시 데이터 출력
    std::vector<char> *buffer = response->getResponseData();
    char str[256= {};
    for(unsigned int i=0; i<buffer->size(); i++){
        sprintf(str, "%s%c", str, (*buffer)[i]);
    }
    
    CCLOG("%s", str);
}
 
cs



결과

1
2
3
4
5
6
response from request to url https://httpbin.org/ip
GET TAG completed
response code : 200
{
  "origin""59.187.203.233"
}
cs


'IT > - 프로그래밍' 카테고리의 다른 글

OpenCV 3채널 영상을 1채널 영상으로 분리하여 영상 출력예제  (0) 2017.04.02
Cocos cJSON 사용  (0) 2017.04.01
IOS Hello World! 출력  (0) 2017.03.30
Cocos 에디트박스 Delegate  (0) 2017.03.29
Cocos EditBox 메서드  (0) 2017.03.28

+ Recent posts