4

如果我访问http://www.microsoft.com/ 将重定向到http://www.microsoft.com/en-us/default.aspx

如何使用 CURL lib 获取响应/重定向 url?

我尝试 curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &reUrl); 这将获得http://www.microsoft.com/

curl_easy_getinfo(curl, CURLINFO_REDIRECT_URL, &reUrl); 这将始终为 NULL

所以谢谢你的帮助

4

1 回答 1

8

CURLOPT_FOLLOWLOCATION 设置1

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

int main(int argc, char** argv)
{
    CURL *curl;
    CURLcode curl_res;

    curl_global_init(CURL_GLOBAL_ALL);

    curl = curl_easy_init();

    if (curl)
    {
        curl_easy_setopt(curl, CURLOPT_URL, "http://www.microsoft.com");
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_easy_setopt(curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"); 

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

        /* Check for errors */ 
        if(curl_res != CURLE_OK)
          fprintf(stderr, "curl_easy_perform() failed: %s\n",
                  curl_easy_strerror(curl_res));

        if(CURLE_OK == curl_res) 
        {
             char *url;
             curl_res = curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &url);

             if((CURLE_OK == curl_res) && url)
                 printf("CURLINFO_EFFECTIVE_URL: %s\n", url);
        }

        /* always cleanup */ 
        curl_easy_cleanup(curl);

        /* we're done with libcurl, so clean it up */ 
        curl_global_cleanup();

    }
    else
    {
        printf("cURL error.\n");
    }

    return 0;
}

你会看见:

CURLINFO_EFFECTIVE_URL: http://www.microsoft.com/en-us/default.aspx
于 2013-04-29T12:21:10.297 回答