Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * HTTP POST with authentiction using "basic" method.
- * Hybrid of anyauthput.c and postinmemory.c
- *
- * Usage:
- * cc basicauthpost.c -lcurl -o basicauthpost
- * ./basicauthpost
- *
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <curl/curl.h>
- struct MemoryStruct {
- char *memory;
- size_t size;
- };
- static size_t WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *context) {
- size_t bytec = size * nmemb;
- struct MemoryStruct *mem = (struct MemoryStruct *)context;
- mem->memory = (char*)realloc(mem->memory, mem->size + bytec + 1);
- if (mem->memory == NULL) {
- printf("not enough memory (realloc returned NULL)\n");
- return 0;
- }
- memcpy(&(mem->memory[mem->size]), ptr, bytec);
- mem->size += bytec;
- mem->memory[mem->size] = 0;
- return nmemb;
- }
- int main(void) {
- CURL *curl;
- CURLcode res;
- struct MemoryStruct chunk;
- chunk.memory = (char*)malloc(1);
- chunk.size = 0;
- chunk.memory[chunk.size] = 0;
- curl_global_init(CURL_GLOBAL_ALL);
- curl = curl_easy_init();
- if (curl) {
- curl_easy_setopt(curl, CURLOPT_URL, "https://api.leoem.com/api/card");
- char *val1 = curl_easy_escape(curl, "tricky & ugly", 0);
- char *val2 = curl_easy_escape(curl, "Hello from cURL!!!", 0);
- char *fields = (char*)malloc(4 + strlen(val1) + 1 + 4 + strlen(val2) + 1);
- size_t fieldSize = 4 + strlen(val1) + 1 + 4 + strlen(val2) + 1;
- sprintf_s(fields, fieldSize, "foo=%s&bar=%s", val1, val2);
- curl_easy_setopt(curl, CURLOPT_POSTFIELDS, fields);
- curl_easy_setopt(curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_BASIC);
- curl_easy_setopt(curl, CURLOPT_USERNAME, "f69a23d1a3b4446c8093cd8684c64f2d");
- curl_easy_setopt(curl, CURLOPT_PASSWORD, "2e001bbfd58443ba9072c512fda0f374");
- curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
- curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
- // The output from the example URL is easier to read as plain text.
- struct curl_slist *headers = NULL;
- headers = curl_slist_append(headers, "Accept: text/plain");
- curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
- // Make the example URL work even if your CA bundle is missing.
- curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
- res = curl_easy_perform(curl);
- if (res != CURLE_OK) {
- fprintf(stderr, "curl_easy_perform() failed: %s\n",
- curl_easy_strerror(res));
- }
- else {
- printf("%s\n", chunk.memory);
- }
- // Remember to call the appropriate "free" functions.
- free(fields);
- curl_free(val1);
- curl_free(val2);
- curl_slist_free_all(headers);
- curl_easy_cleanup(curl);
- free(chunk.memory);
- curl_global_cleanup();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement