bool HttpDownloader::GetReceiveHeaderInfo(const std::string& strUrl, std::map<std::string, std::string>& mapHeaderKeyValue)
{
bool bRet = false;
if (strUrl.empty())
{
return bRet;
}
else
{
CURL *handle = curl_easy_init();
HttpHelper::set_share_handle(handle);
std::string receive_header = "";
char* ctbuf = NULL;
if (handle)
{
curl_easy_setopt(handle, CURLOPT_URL, strUrl.c_str());
curl_easy_setopt(handle, CURLOPT_HEADER, 1);
curl_easy_setopt(handle, CURLOPT_NOBODY, 1);
curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(handle, CURLOPT_MAXREDIRS, 5);
curl_easy_setopt(handle, CURLOPT_HEADERFUNCTION, HttpHelper::RetriveHeaderFunction);
curl_easy_setopt(handle, CURLOPT_HEADERDATA, &receive_header);
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, HttpHelper::RetriveContentFunction);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, NULL);
curl_easy_setopt(handle, CURLOPT_RANGE, "2-");
if ( curl_easy_getinfo(handle, CURLINFO_CONTENT_TYPE, &ctbuf) == 0 && ctbuf )
{
printf("GetReceiveHeaderInfo %s",ctbuf);
}
#ifdef __ANDROID__
curl_easy_setopt(handle, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(handle, CURLOPT_SSL_VERIFYHOST, 0L);
#endif // __ANDROID__
int retry_times = 3;
int http_code = 0;
CURLcode curl_code = curl_easy_perform(handle);
if (curl_code == CURLE_OPERATION_TIMEDOUT)
{
int retry_count = retry_times;
while (retry_count > 0)
{
curl_code = curl_easy_perform(handle);
if (curl_code != CURLE_OPERATION_TIMEDOUT) break;
retry_count--;
}
}
curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &http_code);
if (curl_code == CURLE_OK)
{
double down_file_length = -1.0;
std::string strdown_file_Length = "";
std::string strKey = "filesize";
curl_easy_getinfo(handle, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &down_file_length);
char tempBuffer[64];
sprintf(tempBuffer, "%.2f", down_file_length);
strdown_file_Length = tempBuffer;
mapHeaderKeyValue.insert(std::pair<std::string, std::string>(strKey, strdown_file_Length));
std::string down_file_name = "";
strKey = "filename";
int loc1 = receive_header.find(strKey) + 9;
if(loc1>=9)
{
int loc2 = receive_header.find_first_of(";", loc1);
if (loc2 != std::string::npos)
{
down_file_name = receive_header.substr(loc1, loc2 - loc1);
}
else
{
loc2 = receive_header.find_first_of("\r", loc1);
if (loc2 != std::string::npos)
{
down_file_name = receive_header.substr(loc1, loc2 - loc1);
}
else
{
down_file_name = receive_header.substr(loc1, receive_header.length() - loc1);
}
}
//去掉引号
loc1 = down_file_name.find("\"");
if (loc1 != std::string::npos &&
down_file_name.length()>2)
{
down_file_name = down_file_name.substr(1, down_file_name.length() - 2);
}
}
mapHeaderKeyValue.insert(std::pair<std::string, std::string>(strKey, down_file_name));
bRet = true;
}
else
{
const char* err_string = curl_easy_strerror(curl_code);
}
curl_easy_cleanup(handle);
}
return bRet;
}
}