我写在C语言中使用libcurl库为一个REST API登录到我的网页

问题描述 投票:2回答:1

我使用libcurl库为C语言登录到我的网站每天page.but我收到401未授权错误的时间写一个REST API。下面是代码

int main(int argc, const char* args[])
{
    CURL *curl;
    CURLcode res;
    struct curl_slist *header = NULL;
    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();
    if (curl) {      
        curl_easy_setopt(curl, CURLOPT_URL, "https://samplewebpage.com/rest/api/2/issue");
        curl_easy_setopt(curl, CURLOPT_POST, 1L);       
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);      
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, FALSE);      
        header = curl_slist_append(header, "Content-Type: application/x-www-form-urlencoded");   
        header = curl_slist_append(header, "Authorization: Basic ");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);        
        curl_easy_setopt(curl, CURLOPT_USERPWD, "SharedIP:SharedIP@123");       
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
        /* Perform the request, res will get the return code */       
        res = curl_easy_perform(curl);
        curl_slist_free_all(header);
        /* Check for errors */
        if (res != CURLE_OK)
            fprintf(stderr, "curl_easy_perform() failed: error %d %s\n", res,
                curl_easy_strerror(res));
        /* always cleanup */
        curl_easy_cleanup(curl);
    }
    curl_global_cleanup();
    return 0;
}
php c libcurl
1个回答
1
投票

你做的做它自己的混合,让libcurl中做到这一点,都只有一半。

你自己

您可以添加HTTP授权头自己,但这并不是有效的,例如标题:

header = curl_slist_append(header, "Authorization: Basic ");

你缺少的base64(“用户:密码”)遵循“基本法”的一部分。与此类似:

header = curl_slist_append(header, "Authorization: Basic aWFtOm15OjtzZWxm");

让libcurl的做

然后,你没有手动传递的Authorization:头,而是问的libcurl来处理身份验证。你这样做,通过设置像你已经做CURLOPT_USERPWD选项 - 但在你的情况,你通过自己的自定义破坏它(碎)标头将覆盖在内部生成的头。

© www.soinside.com 2019 - 2024. All rights reserved.