Skip to content
Snippets Groups Projects
Commit 7603d0be authored by Arun muthusamy's avatar Arun muthusamy
Browse files

add: http get request func

parent 76abadae
No related branches found
No related tags found
No related merge requests found
/***************************************************************************
*
* Project: dongle
*
*
***************************************************************************/
#include <stdio.h>
#include <curl/curl.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define BUFFER_SIZE (256 * 1024)
typedef enum{
get_request,
post_request
} request_type;
struct write_result
{
char *data;
int pos;
};
static size_t write_response(void *ptr, size_t size, size_t nmemb, void *stream)
{
struct write_result *result = (struct write_result *)stream;
if(result->pos + size * nmemb >= BUFFER_SIZE - 1)
{
fprintf(stderr, "error: too small buffer\n");
return 0;
}
memcpy(result->data + result->pos, ptr, size * nmemb);
result->pos += size * nmemb;
return size * nmemb;
}
static char *request(const char *url)
{
CURL *curl = NULL;
CURLcode status;
char *data = NULL;
long code;
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
printf("init curl session\n");
if(!curl)
goto error;
data = malloc(BUFFER_SIZE);
if(!data)
goto error;
struct write_result write_result = {
.data = data,
.pos = 0
};
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_COOKIEJAR, "cookies.txt"); //Save the cookie from the server to cookie.txt
curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "cookies.txt"); //Read locally stored cookies
sleep(1);
curl_easy_setopt(curl, CURLOPT_URL, "http://192.168.8.1/api/monitoring/status");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_response);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &write_result);
status = curl_easy_perform(curl);
if(status != 0)
{
printf("Error: unable to request data from %s:\n", url);
printf(": %s\n", curl_easy_strerror(status));
goto error;
}
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);
if(code != 200)
{
printf("error: server responded with code %ld\n", code);
goto error;
}
curl_easy_cleanup(curl);
curl_global_cleanup();
data[write_result.pos] = '\0';
printf("Data is: %s\n", data);
return data;
error:
printf("error");
if(data) {
printf("error occured: free data");
free(data);
}
if(curl) {
printf("error occured: easy cleanup curl");
curl_easy_cleanup(curl);
}
curl_global_cleanup();
return NULL;
}
int main() {
request("http://192.168.8.1/html/index.html");
//request(post_request, "http://192.168.8.1/api/webserver/SesTokInfo");
return 0;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment