-
Notifications
You must be signed in to change notification settings - Fork 1
/
shortenthis.c
78 lines (70 loc) · 2.33 KB
/
shortenthis.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
#include<stdio.h>
#include<json.h>
#include<stdlib.h>
#include<regex.h>
#include<string.h>
#include<curl/curl.h>
struct string {
char* res;
size_t len;
};
void init_string(struct string *s) {
s->len = 0;
s->res = malloc(s->len+1);
if (s->res == NULL) {
fprintf(stderr, "malloc() has failed\n");
exit(EXIT_FAILURE);
}
s->res[0]='\0';
}
size_t writeOutput(void *ptr, size_t size, size_t nmemb, struct string* s) {
size_t new_len = s->len+size*nmemb;
s->res = realloc(s->res, new_len+1);
if (s->res == NULL) {
fprintf(stderr, "realloc() failed\n");
exit(EXIT_FAILURE);
}
memcpy(s->res+s->len, ptr, size*nmemb);
s->res[new_len] = '\0';
s->len = new_len;
return size*nmemb;
}
int main(int argc, char *argv[]) {
if (argv[1] == NULL) {
printf("Please enter a URL too be shortened");
return(1);
}
struct json_object *req_body,*res_body,*short_url;
struct string res;
init_string(&res);
CURL* handle;
CURLcode rcode;
char *url = "https://www.googleapis.com/urlshortener/v1/url?key=YOUR_API_KEY";
struct curl_slist *headers = NULL;
handle = curl_easy_init();
req_body = json_object_new_object();
json_object_object_add(req_body, "longUrl", json_object_new_string(argv[1]));
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, "Accept: application/json");
curl_easy_setopt(handle, CURLOPT_URL, url);
curl_easy_setopt(handle, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(handle, CURLOPT_SSL_VERIFYHOST, 0L);
curl_easy_setopt(handle, CURLOPT_CUSTOMREQUEST, "POST");
curl_easy_setopt(handle, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(handle, CURLOPT_POSTFIELDS, json_object_to_json_string(req_body));
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, writeOutput);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, &res);
rcode = curl_easy_perform(handle);
if (rcode != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed : %s .\n", curl_easy_strerror(rcode));
}
res_body = json_tokener_parse(res.res);
json_object_object_get_ex(res_body, "id", &short_url);
printf("%s\n", json_object_to_json_string_ext(short_url, JSON_C_TO_STRING_SPACED | JSON_C_TO_STRING_PRETTY));
free(res.res);
curl_easy_cleanup(handle);
json_object_put(res_body);
json_object_put(req_body);
json_object_put(short_url);
return 0;
}