如果我访问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
非常感谢您的帮助
答案 0 :(得分:8)
#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