首页 > 解决方案 > 在 C++ 中将代理身份验证与 LibCurl 一起使用

问题描述

我尝试在 c++ 中使用 libcurl 创建 http get 请求。首先我使用了这段代码(没有代理并且它有效)

#include <stdio.h>
#include <curl/curl.h>
#include <iostream>

int main(void)
{

   CURL* curl;
    CURLcode res;

    curl = curl_easy_init();
    if (curl) {
     
        curl_easy_setopt(curl, CURLOPT_URL, "https://stackoverflow.com/");


        /* Perform the request, res will get the return code */
        res = curl_easy_perform(curl);

        /* always cleanup */
        curl_easy_cleanup(curl);
    }
    return 0;
}

其次,我尝试使用带有用户名和密码的代理身份验证,但没有得到任何响应。

#include <stdio.h>
#include <curl/curl.h>
#include <iostream>

    int main(void)
    {
    
       CURL* curl;
        CURLcode res;
    
        curl = curl_easy_init();
        if (curl) {
         
            curl_easy_setopt(curl, CURLOPT_URL, "https://stackoverflow.com/");
            curl_easy_setopt(curl, CURLOPT_PROXY, "here is my proxy");
            curl_easy_setopt(curl, CURLOPT_USERNAME, "my username");
            curl_easy_setopt(curl, CURLOPT_PASSWORD, "my pass");
    
            /* Perform the request, res will get the return code */
            res = curl_easy_perform(curl);
    
            /* always cleanup */
            curl_easy_cleanup(curl);
        }
        return 0;
    }

我不知道为什么它不起作用。 代理在 c# 中经过测试并且可以工作

标签: c++libcurl

解决方案


找到答案只需将CURLOPT_USERNAME替换为CURLOPT_PROXYUSERNAME 并将CURLOPT_PASSWORD替换为 CURLOPT_PROXYPASSWORD。工作代码

#include <stdio.h>
#include <curl/curl.h>
#include <iostream>

int main(void)
{

    CURL* curl = curl_easy_init();
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "https://stackoverflow.com/");
        curl_easy_setopt(curl, CURLOPT_PROXY, "http://proxy:port");
        curl_easy_setopt(curl, CURLOPT_PROXYUSERNAME, "username");
        curl_easy_setopt(curl, CURLOPT_PROXYPASSWORD, "password");
       curl_easy_perform(curl);
        curl_easy_cleanup(curl);
    }
}

推荐阅读