User Tools

Site Tools


example_of_data_access_from_c_c

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

example_of_data_access_from_c_c [2018/12/11 12:14] (current)
emozolyak created
Line 1: Line 1:
 +====== An example of data access from C/C++ ======
 +
 +An example of C code for executing a query to the WebHMI API.
 +<code C>
 +#include <cstdlib>
 +#include <iostream>
 +#include <curl/curl.h>
 +#include <curl/easy.h>
 +#include <fstream>
 +
 +using namespace std;
 +size_t write_func(void *ptr, size_t size, size_t nmemb, void *userdata)
 +{
 +        cout.write( (char * ) ptr, size*nmemb); // just output response to screen
 +        return size * nmemb;
 +}
 +
 +int main(int argc, char** argv) {
 +    
 +    CURL *curl;
 +    CURLcode res;
 +
 +    char errorBuffer[CURL_ERROR_SIZE];
 +
 +    // Create the GET request
 +    struct curl_slist *headers = NULL;
 +    headers = curl_slist_append(headers, "X-WH-APIKEY: F3C74230818DA487BB2017CE5D0290F4DABCAFD7"); // API Key. If API Key is wrong API will return 401 status code.
 +    headers = curl_slist_append(headers, "X-WH-START: 1391165350"); // Start time for report. Unixtime
 +    headers = curl_slist_append(headers, "X-WH-END: 1391186951"); // End time for report. Unixtime
 +    headers = curl_slist_append(headers, "Accept: application/json");  // Currenlty we support JSON ONLY, required header
 +    headers = curl_slist_append(headers, "Content-Type: application/json"); // Currenlty we support JSON ONLY, required header
 +
 +
 +    // Init CURL
 +    curl = curl_easy_init();
 +
 +    if(curl) {
 +        curl_easy_setopt(curl, CURLOPT_URL, "http://192.168.0.1/api/event-data/1");  // 1 = ID of report
 +        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
 +        curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer);
 +        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_func);
 +
 +        // Attempt to Connect the Server
 +        res = curl_easy_perform(curl);
 +
 +        if (res == CURLE_OK) {
 +            long http_code = 0;
 +            curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &http_code);
 +            if (http_code == 200 && res != CURLE_ABORTED_BY_CALLBACK) {
 +                cout << endl << "Success!"<< endl;
 +            } else {
 +                cout << endl << "Error! Code: " << http_code << endl;
 +            }
 +        } else {
 +            cout << "Connection Failed! Error: " << errorBuffer << endl;
 +        }
 +
 +        // Close the connection
 +        curl_easy_cleanup(curl);
 +    }
 +    
 +    return 0;
 +}
 +</code>