• 분류 전체보기
    • 갈무리
    • 씨플플
    • SPRING
    • PI
    • ALGORITHM
    • DIARY
    • (∗❛ᴗ❛∗)
    • (●'◡'●)
    • 민디의 취준일기 (202301~)
  1. 라즈베리파이4 snowboy 설치하기 2020.06.30
  2. 라즈베리파이 처음 시작하기 (필요한 물품 설명) 2020.02.15
  3. 라즈베리파이 3B+ 4B 아두이노 시리얼통신 (UART - Tx, Rx 핀 사용) 2020.01.24
  4. vnc연결 성공해따 2018.11.13
[curl] 라즈베리파이 http 통신하기 #PI
2020. 8. 12.

1. curl 라이브러리 설치

$ sudo apt-get install libcurl4-openssl-dev 

 

실행

$ gcc httptest.c -o httptest -lcurl

 

예제


#include <stdio.h>
#include <string>
#include <curl/curl.h>

int main(void) {
    CURL* curl;
    CURLcode res;
    long statLong;
    char* statString = NULL;

    curl = curl_easy_init();
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "https://www.naver.com");
        /* example.com is redirected, so we tell libcurl to follow redirection */
        //curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);

        // request 요청 결과를 화면에 출력하게 설정
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, stdout);
        
        /* Perform the request, res will get the return code */

        // action!
        // 미리 설정한 curl 로 url에 request
        res = curl_easy_perform(curl);
        /* Check for errors */
        if (res != CURLE_OK) {

            fprintf(stderr, "curl_easy_perform() failed: %s\n",
                curl_easy_strerror(res));

        }
        else {
            // get some info about the xfer:
            double statDouble;
            long statLong;
            char* statString = NULL;

            // HTTP 응답코드를 얻어온다. 
            if (CURLE_OK == curl_easy_getinfo(curl, CURLINFO_HTTP_CODE, &statLong)) {
                printf("response code: %ld", statLong);
                //std::cout << "Response code:  " << statLong << std::endl ;
            }

            // Content-Type 를 얻어온다.
            if (CURLE_OK == curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &statString)) {
                printf("Content type: %s", statString);
            }

        }
        /* always cleanup */
        curl_easy_cleanup(curl);
    }
    return 0;
}

 

밑은 request 시 받는 response Data를 빼내는 callback 함수를 구현한 코드.

구조체 ResponseData 안 responseBody에 담기도록 구현했습니다.

 

티스토리툴바