ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • CURL 활용
    Language/C & C++ 2023. 2. 17. 20:35

    Windows 와 Linux 에서 활용할 수 있는 크로스플랫폼 HTTP Library 중 하나인 CURL의 사용법에 대하여 안내합니다.

    Windows 환경에서는 multi_perform 진행시 로직에 따라 메모리에 문제가 발생되는 것으로 확인되어 따로 안내하지않습니다.

    해당 라이브러리는 HTTP 의 기본적인 Header, Body, Action 에 대한 지정히 가능하며 각기 콜백을 통하여 진행률 표기, 디버그 로깅, Response 데이터 확인이 가능토록 지원하고 있습니다.

    CURL Lib 을 별도로 Wrapping 하여 보다 편하게 활용토록 하는 오픈소스들도 존재합니다.

    아래는 Header 지정, Body 지정, 각 설정에 대하여 활용하는 방안에 대하여 가이드하는 코드입니다.

            CURL* CURL_ = curl_easy_init(); // Init
    
            std::string strPostData;//("TEST DATA INPUT");
    
            //struct curl_slist *headers=NULL;/* init to NULL is important */
            //headers = curl_slist_append(headers, "Content-Type: application/json");
            //headers = curl_slist_append(headers, "Content-Length: " + strPostData.length());
            //curl_easy_setopt(CURL_, CURLOPT_HTTPHEADER, headers);
    
            // HTTP Request Options
            curl_easy_setopt(CURL_, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
            curl_easy_setopt(CURL_, CURLOPT_PROTOCOLS, CURLPROTO_HTTP);
            curl_easy_setopt(CURL_, CURLOPT_USE_SSL, CURLUSESSL_ALL);
            curl_easy_setopt(CURL_, CURLOPT_SSL_VERIFYHOST, 0);
            curl_easy_setopt(CURL_, CURLOPT_SSL_VERIFYPEER, 0);
            curl_easy_setopt(CURL_, CURLOPT_WRITEFUNCTION, &CurlWriteCallback);
            curl_easy_setopt(CURL_, CURLOPT_WRITEDATA, (void *)this);
            curl_easy_setopt(CURL_, CURLOPT_POST, 1);
            curl_easy_setopt(CURL_, CURLOPT_POSTFIELDS, strPostData.c_str());
            curl_easy_setopt(CURL_, CURLOPT_POSTFIELDSIZE, strPostData.size());
            curl_easy_setopt(CURL_, CURLOPT_NOSIGNAL, 1L);
            curl_easy_setopt(CURL_, CURLOPT_URL, "http://127.0.0.1:8080/test");
            //curl_easy_setopt(CURL_, CURLOPT_TCP_KEEPALIVE,  1L);
            //curl_easy_setopt(CURL_, CURLOPT_TCP_KEEPIDLE, 120L);
            //curl_easy_setopt(CURL_, CURLOPT_TCP_KEEPINTVL, 60L);
            //curl_easy_setopt(CURL_, CURLOPT_MAXAGE_CONN, 3L);
    
            //curl_easy_setopt(CURL_, CURLOPT_TIMEOUT_MS, 3000);
            curl_easy_setopt(CURL_, CURLOPT_VERBOSE, 1L);
            //curl_easy_setopt(CURL_, CURLOPT_DEBUGFUNCTION, DebugCallback);
            //curl_easy_setopt(CURL_, CURLOPT_NOPROGRESS, 0L);
    
            //curl_easy_setopt(CURL_, CURLOPT_PREREQFUNCTION, prereq_callback);
            //curl_easy_setopt(CURL_, CURLOPT_PREREQDATA, &strPostData);
    
            std::cout << "curl request add" << std::endl;
    
            curl_easy_perform(CURL_);
Designed by Tistory.