首页 > 解决方案 > Libcurl HTTP POST 请求

问题描述

我目前正在尝试编写一个 HTTP 发布请求,以便能够从我的程序在网站上注册。当我运行它时,我没有收到任何错误,甚至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();

标签: c++postlibcurl

解决方案


请注意响应中的这一行:

< HTTP/1.1 415 Unsupported Media Type

您可能希望使用curl_easy_getinfowith从响应CURLINFO_RESPONSE_CODE中检索和检查HTTP 状态代码。

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


推荐阅读