libCURL 不遵循重定向(即使使用 1L FOLLOW_LOCATION)

libCURL doesn't follow redirects (even with FOLLOW_LOCATION 1L)

本文关键字:1L FOLLOW LOCATION 重定向 libCURL      更新时间:2023-10-16

我正在尝试编写一个从sourceforge下载的代码片段。这是代码,您可能会注意到我明确设置了CURLOPT_FOLLOWLOCATION但似乎没有效果

int main(void) {
    CURL *curl = curl_easy_init();
    FILE *fp;
    CURLcode res;
    const char *url = "http://sourceforge.net/projects/mpc-hc/files/MPC%20HomeCinema%20-%20x64/MPC-HC_v1.7.7_x64/MPC-HC.1.7.7.x64.exe";
    char outfilename[FILENAME_MAX] = "/home/snake91/example.exe";
    if (curl) {
        fp = fopen(outfilename,"w+");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
        curl_easy_setopt(curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
         curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        fwrite(buffer2.c_str (), buffer2.length (), sizeof(char), fp);
        fclose(fp);
    }
    return 0;
}

寻找解决方案,我发现有一个 CURL (-L) 的参数可以完成这项工作,库是否有等效的东西?

ps 这是详细标志的输出...

* Hostname was NOT found in DNS cache
*   Trying 216.34.181.60...
* Connected to sourceforge.net (216.34.181.60) port 80 (#0)
> GET /projects/mpc-hc/files/MPC%20HomeCinema%20-%20x64/MPC-HC_v1.7.7_x64/MPC-HC.1.7.7.x64.exe HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)
Host: sourceforge.net
Accept: */*
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Server: BigIP
* HTTP/1.0 connection set to keep alive!
< Connection: Keep-Alive
< Content-Length: 3047
< 
* Connection #0 to host sourceforge.net left intact

-L 设置CURLOPT_FOLLOWLOCATION

但是,正如您在响应标头中看到的那样,您会得到 200 OK 返回,这不是 HTTP 重定向,因此 libcurl 无需遵循。如果该URL确实有重定向,则要么使用HTML元刷新标记完成,要么使用javascript进行 - libcurl都不支持。