Libcurl HTTP POST 请求

Libcurl HTTP POST request

我目前正在尝试编写一个 HTTP post 请求,以便能够通过我的程序在网站上注册。 当我 运行 它没有错误,甚至 CURLOPT_VERBOSE 说一切都成功了。

希望大家多多指教或帮助,在此先谢过了!

详细输出:

    *   Trying 151.139.128.8:443...
* Connected to fontawesome.com (151.139.128.8) port 443 (#0)
> POST /api/account HTTP/1.1
Host: fontawesome.com
User-Agent: M1000/1.0
Accept: */*
Content-Type: application/vnd.api+json; charset=UTF-8
Content-Length: 103

* upload completely sent off: 103 out of 103 bytes
* Mark bundle as not supporting multiuse
< HTTP/1.1 415 Unsupported Media Type
< Date: Fri, 07 Aug 2020 12:45:12 GMT
< Cache-Control: max-age=0, private, must-revalidate
< cross-origin-window-policy: deny
< Server: Cowboy
< Strict-Transport-Security: max-age=31536000; preload; includeSubDomains
< X-Content-Type-Options: nosniff
< x-download-options: noopen
< X-Frame-Options: SAMEORIGIN
< x-permitted-cross-domain-policies: none
< x-request-id: Fij9D99y9W_KuwABOosh
< X-XSS-Protection: 1; mode=block
< X-HW: 1596804312.cds067.am5.hn,1596804312.cds153.am5.sc,1596804312.cds153.am5.p
< Connection: keep-alive
< Content-Length: 0
<
* Connection #0 to host fontawesome.com left intact
OK!

我的代码:

curl_global_init(CURL_GLOBAL_ALL);
CURL* curl = curl_easy_init();
CURLcode res;

if (curl) {     
    const char* c = "https://fontawesome.com/api/account";
    curl_easy_setopt(curl, CURLOPT_URL, c);
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
    curl_easy_setopt(curl, CURLOPT_POST, 1L);       
    curl_easy_setopt(curl, CURLOPT_USERAGENT, "M1000/1.0");

    const char *data = "{\"meta\":{},\"data\":{\"type\":\"account\",\"attributes\":{\"email\":\"email@domain.com\",\"is - free\":true}}}";
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(data));
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);

    res = curl_easy_perform(curl);      

    if (res != 0) {
        curl_easy_cleanup(curl);
        curl_global_cleanup();
        F.SetError__(res);
        return;
    }
    else
    {
        F.Print("OK!");
    }
}
curl_easy_cleanup(curl);
curl_global_cleanup();

请注意回复中的这一行:

< HTTP/1.1 415 Unsupported Media Type

您可能希望将 curl_easy_getinfoCURLINFO_RESPONSE_CODE 结合使用来检索和检查响应中的 HTTP status code

根据 API,响应 415 可能具有不同的含义。在这种情况下,服务器可能希望请求中有 Content-Type: application/json header。

感谢 KiNgMaR 我修复了它。 我开始更多地了解 headers 和 HTTP 请求,终于找到了问题所在。我一直在为服务器发送不支持的媒体类型。经过一番研究,我发现服务器接受的 Content-Type 是 "Content-Type: application/vnd.api+json"

我添加到代码中的内容:

list = curl_slist_append(list, "Content-Type: application/vnd.api+json");
list = curl_slist_append(list, "Accept: application/vnd.api+json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list);