61 lines
1.6 KiB
C
61 lines
1.6 KiB
C
#include "http.h"
|
|
|
|
#include <string.h>
|
|
#include <curl/curl.h>
|
|
#include <stdlib.h>
|
|
|
|
int curl_setup = 0;
|
|
char* request(char *url)
|
|
{
|
|
// initialize curl on the first call of this function
|
|
if(curl_setup == 0)
|
|
{
|
|
curl_global_init(CURL_GLOBAL_DEFAULT);
|
|
curl_setup=1;
|
|
}
|
|
|
|
struct httpResponse_t httpResponse;
|
|
httpResponse.response = malloc(1);
|
|
httpResponse.size = 0;
|
|
CURL *httpHandler = curl_easy_init();
|
|
CURLcode return_code;
|
|
if(httpHandler) {
|
|
for(int i=0;i<128;i++)
|
|
{
|
|
fprintf(stderr,"%x",url[i]);
|
|
}
|
|
curl_easy_setopt(httpHandler,CURLOPT_URL, url);
|
|
curl_easy_setopt(httpHandler,CURLOPT_WRITEFUNCTION, httpResponseCallback);
|
|
curl_easy_setopt(httpHandler,CURLOPT_USERAGENT, "cWikiBot/0.1 (https://git.zom.bi/cpp/cWikiBot; cpp@zom.bi) libcurl4/7.64.0");
|
|
curl_easy_setopt(httpHandler,CURLOPT_WRITEDATA, (void *)&httpResponse);
|
|
return_code = curl_easy_perform(httpHandler);
|
|
}
|
|
else
|
|
{
|
|
fprintf(stderr, "CURL Error");
|
|
return NULL;
|
|
}
|
|
if(return_code != CURLE_OK)
|
|
{
|
|
fprintf(stderr, "HTTP Error: %s\n",curl_easy_strerror(return_code));
|
|
return NULL;
|
|
}
|
|
return httpResponse.response;
|
|
}
|
|
size_t httpResponseCallback(char *data, size_t wordlength, size_t bytecount, void *out)
|
|
{
|
|
// wordlength should be always 1, but this appears to be more secure.
|
|
size_t size = wordlength * bytecount;
|
|
struct httpResponse_t *mem = (struct httpResponse_t *) out;
|
|
|
|
char *newData = realloc(mem->response, mem->size + size +1);
|
|
if(newData == NULL)
|
|
return 0;
|
|
mem->response = newData;
|
|
memcpy(&(mem->response[mem->size]), data, size);
|
|
mem->size += size;
|
|
// Null-terminate the byte chunk, to effectively have a C-String.
|
|
mem->response[mem-> size] = 0;
|
|
|
|
return size;
|
|
}
|