c++下载文件(考虑浏览器缓冲)

来源:互联网 发布:linux中查看端口 编辑:程序博客网 时间:2024/06/05 01:00
CString DownloadFile(CString strURL,int type){//初始化数据//BYTE datalen[5];int len = 0;CHttpFile* pfile = NULL;CInternetSession session("HttpClient");    session.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 10 * 1000) ;//session.SetOption(INTERNET_OPTION_DATA_RECEIVE_TIMEOUT, 1000*15);//session.SetOption(INTERNET_OPTION_DATA_SEND_TIMEOUT, 1000*10);    session.SetOption(INTERNET_OPTION_CONNECT_BACKOFF, 1000) ;    session.SetOption(INTERNET_OPTION_CONNECT_RETRIES, 2) ;//char m_buffer[1000];//memset(m_buffer,0x00,len);CString strData;try{//这里加入参数,否则第二次抓取相同文件时会获取缓冲区数据,导致数据没更新   2009-2-3 shenay//使用文本数据  |强制重读取数据| 不保留缓冲区pfile = (CHttpFile *)session.OpenURL(strURL,1,INTERNET_FLAG_TRANSFER_ASCII|INTERNET_FLAG_RELOAD|INTERNET_FLAG_DONT_CACHE);DWORD dwStatusCode;pfile->QueryInfoStatusCode(dwStatusCode);//返回网络请求状态参数//若能读到网络数据,则开始解析DAY文件if(dwStatusCode==HTTP_STATUS_OK){CString cslen;pfile->QueryInfo(HTTP_QUERY_CONTENT_LENGTH,cslen);len = atoi(cslen);char *pBuffer = new char[len+1];int backlen = pfile->Read(pBuffer,len);if(type == 0){strData = pBuffer;strData = strData.Left(len);}else if(type == 1){CFile file;if(file.Open(m_strSysConfig,CFile::modeCreate|CFile::modeWrite)){file.Write(pBuffer,len);file.Close();}}else if(type == 2){char path[255];SHGetSpecialFolderPath(0,path,CSIDL_DESKTOPDIRECTORY,0);CString strSavePath(path);strSavePath +=  "\\新版新闻操作程序.rar";//解密for(int i=0; i<len; i++)pBuffer[i] ^= 4182;CFile file;if(file.Open(strSavePath,CFile::modeCreate|CFile::modeWrite)){file.Write(pBuffer,len);file.Close();}}pfile->Close();delete pfile;delete []pBuffer;}}catch(CInternetException * pException){CString strMsg = "验证程序版本失败,请确认网络连接状况!\r\n";char szErr[1000];if(pException->GetErrorMessage(szErr,1000))strMsg += szErr;strData = szErr;}session.Close();delete session;return strData;}

原创粉丝点击