我正在尝试使用curl.h库发送带有HTTPS通信的POST类型消息,但我有些疑惑:
必须将证书放在文件中(可能在项目文件夹中),或者可以动态获取证书(例如PostMan)。
如何发送数据格式。
如何接收数据等于HTTP?
这是我的计划:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <curl/curl.h>
BYTE str[20];
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 post_function()
{
CURL *post;
CURLcode ret;
struct string s;
init_string(&s);
curl_global_init(CURL_GLOBAL_DEFAULT);
post = curl_easy_init();
curl_easy_setopt(post, CURLOPT_CUSTOMREQUEST, "POST");
curl_easy_setopt(post, CURLOPT_URL, "https://example.com/post.php");
curl_easy_setopt(post, CURLOPT_WRITEFUNCTION, writefunc);
curl_easy_setopt(post, CURLOPT_WRITEDATA, &s);
curl_easy_setopt(post, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(post, CURLOPT_SSL_VERIFYHOST, 0L);
curl_easy_setopt(post, CURLOPT_POSTFIELDS, "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"data\"\r\n\r\nName\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--");
ret = curl_easy_perform(post);
if(ret == CURLE_OK)
{
sprintf(str, "Msj: %s\n", s.ptr);
}
else
{
//ERROR
}
curl_easy_cleanup(post);
curl_global_cleanup();
}
int main(int argc, char const *argv[])
{
post_function();
return 0;
}