1.环境Windows
2.依赖库文件
头文件:
<curl.h>
lib:
- libcurl.a
- libcurl.dll.a
dll:
libcurl.dll
下载地址:https://curl.haxx.se/windows/
3.程序
//#define CURL_STATICLIB
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include <frozen-master/frozen.h>
#define myurl "www.helloworld.com"
struct string {
char *ptr;
size_t len;
};
void init_string(struct string *s) {
s->len = 0;
s->ptr = malloc(s->len + 1);
if (s->ptr == NULL) {
fprintf(stderr, "malloc() failed\n");
exit(EXIT_FAILURE);
}
s->ptr[0] = '\0';
}
size_t writefunc(void *ptr, size_t size, size_t nmemb, struct string *s)
{
size_t new_len = s->len + size * nmemb;
s->ptr = realloc(s->ptr, new_len + 1);
if (s->ptr == NULL) {
fprintf(stderr, "realloc() failed\n");
exit(EXIT_FAILURE);
}
memcpy(s->ptr + s->len, ptr, size*nmemb);
s->ptr[new_len] = '\0';
s->len = new_len;
return size * nmemb;
}
int main(void)
{
CURL *curl;
CURLcode res;
char *mytopic = NULL;
char *mybootstrap_servers = NULL;
curl = curl_easy_init();
if (curl) {
struct string s;
init_string(&s);
struct curl_slist *chunk = NULL;
/* Remove a header curl would otherwise add by itself */
chunk = curl_slist_append(chunk, "Agent-Role:Your_Role");
/* Add a custom header */
chunk = curl_slist_append(chunk, "Agent-User:Username");
/* Modify a header curl otherwise adds differently */
chunk = curl_slist_append(chunk, "Agent-Password:Password");
/* Add a header with "blank" contents to the right of the colon. Note that
we're then using a semicolon in the string we pass to curl! */
//chunk = curl_slist_append(chunk, "X-silly-header;");
/* set our custom set of headers */
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
//curl_easy_setopt(curl, CURLOPT_URL, "https://example.com");
curl_easy_setopt(curl, CURLOPT_URL, myurl);
/* example.com is redirected, so we tell libcurl to follow redirection */
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
/* Check for errors */
if (res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
printf("%s\n", s.ptr);
free(s.ptr);
/* always cleanup */
curl_easy_cleanup(curl);
}
return 0;
}
另附官方的简单curl使用例程(具体参考官网:https://curl.haxx.se):
#include <stdio.h>
#include <curl/curl.h>
int main(void)
{
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "https://example.com");
/* example.com is redirected, so we tell libcurl to follow redirection */
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
/* Check for errors */
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
/* always cleanup */
curl_easy_cleanup(curl);
}
return 0;
}
参考:
1.https://curl.haxx.se/libcurl/c/http-post.html