-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhttp.c
97 lines (73 loc) · 1.97 KB
/
http.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <string.h>
#include "http.h"
static CURL *curl;
struct MemoryStruct {
char *memory;
size_t size;
};
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)userp;
mem->memory = realloc(mem->memory, mem->size + realsize + 1);
if(mem->memory == NULL) {
/* out of memory! */
printf("not enough memory (realloc returned NULL)\n");
return 0;
}
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
static void http_prepare(const char *url, struct MemoryStruct *chunk)
{
curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "tkuftools/0.1 (https://www.tal.org/projects/tkuftools)");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)chunk);
}
static int http_get(const char *url, struct MemoryStruct *chunk)
{
long http_code=0;
CURLcode res;
chunk->memory = malloc(8192);
chunk->size = 0;
http_prepare(url, chunk);
res=curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
if(res!=CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
curl_easy_cleanup(curl);
return -1;
}
curl_easy_cleanup(curl);
//printf("Downloaded: %d\n", chunk.size);
//fprintf(stderr, "\n\n%s\n\n", chunk.memory);
if (http_code!=200)
return http_code;
return 0;
}
json_object *http_get_json(const char *url)
{
struct MemoryStruct chunk;
if (http_get(url, &chunk)!=0)
return NULL;
json_object *obj = json_tokener_parse(chunk.memory);
if (!obj) {
fprintf(stderr, "Invalid JSON\n");
return NULL;
}
free(chunk.memory);
return obj;
}
void http_init()
{
curl_global_init(CURL_GLOBAL_DEFAULT);
}
void http_deinit()
{
curl_global_cleanup();
}