BOOL CUpdateThread::Download( LPCTSTR lpszUrl, LPCTSTR lpszSavePath, ULONG uSize) { DWORD dwServiceType; CString strServer; CString strObject; INTERNET_PORT nPort; BOOL bResult = FALSE; if (AfxParseURL(lpszUrl, dwServiceType, strServer, strObject, nPort)) { CHttpConnection *conn = NULL; CHttpFile *file = NULL; UpdateSubProgress(0); try { int flags = INTERNET_FLAG_EXISTING_CONNECT; if (dwServiceType == AFX_INET_SERVICE_HTTPS) { flags |= INTERNET_FLAG_SECURE | INTERNET_FLAG_IGNORE_CERT_CN_INVALID | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID; } conn = m_Session.GetHttpConnection(strServer, nPort); file = conn->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject, NULL, 1, NULL, NULL, flags); file->SendRequest(); UpdateSubProgress(10); DWORD dwStatus = 0; file->QueryInfoStatusCode(dwStatus); if (dwStatus == 200) { CFile localFile(lpszSavePath, CFile::modeReadWrite | CFile::shareExclusive | CFile::modeCreate); char buf[512]; UINT nCount = 0; ULONG uTotal = 0; while ((nCount = file->Read(buf, 1)) > 0) { localFile.Write(buf, nCount); uTotal += nCount; if (uSize > 0) UpdateSubProgress(10 + 90.0 * uTotal / uSize); } localFile.Close(); bResult = TRUE; } } catch (CException *e) { e->ReportError(); e->Delete(); } if (file) { file->Close(); delete file; } if (conn) { conn->Close(); delete conn; } UpdateSubProgress(100); }; return bResult; }
BOOL CDlgView::Download(const CString& strFileURLInServer, //待下载文件的URL const CString & strFileLocalFullPath)//存放到本地的路径 { ASSERT(strFileURLInServer != ""); ASSERT(strFileLocalFullPath != ""); CInternetSession session(_T("test")); CHttpConnection* pHttpConnection = NULL; CHttpFile* pHttpFile = NULL; CString strServer, strObject; INTERNET_PORT wPort; DWORD dwType; const int nTimeOut = 2000; session.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, nTimeOut); //重试之间的等待延时 session.SetOption(INTERNET_OPTION_CONNECT_RETRIES, 1); //重试次数 char* pszBuffer = NULL; try { AfxParseURL(strFileURLInServer, dwType, strServer, strObject, wPort); pHttpConnection = session.GetHttpConnection(strServer, wPort); pHttpFile = pHttpConnection->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject,NULL,1,NULL,NULL,INTERNET_FLAG_TRANSFER_ASCII|INTERNET_FLAG_RELOAD); if(pHttpFile->SendRequest() == FALSE) return false; DWORD dwStateCode; pHttpFile->QueryInfoStatusCode(dwStateCode); if(dwStateCode == HTTP_STATUS_OK) { HANDLE hFile = CreateFile(strFileLocalFullPath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); //创建本地文件 if(hFile == INVALID_HANDLE_VALUE) { pHttpFile->Close(); pHttpConnection->Close(); session.Close(); return false; } char szInfoBuffer[1000]; //返回消息 DWORD dwFileSize = 0; //文件长度 DWORD dwInfoBufferSize = sizeof(szInfoBuffer); BOOL bResult = FALSE; bResult = pHttpFile->QueryInfo(HTTP_QUERY_CONTENT_LENGTH, (void*)szInfoBuffer,&dwInfoBufferSize,NULL); dwFileSize = atoi(szInfoBuffer); const int BUFFER_LENGTH = 1024 * 10; pszBuffer = new char[BUFFER_LENGTH]; //读取文件的缓冲 DWORD dwWrite, dwTotalWrite; dwWrite = dwTotalWrite = 0; UINT nRead = pHttpFile->Read(pszBuffer, BUFFER_LENGTH); //读取服务器上数据 while(nRead > 0) { WriteFile(hFile, pszBuffer, nRead, &dwWrite, NULL); //写到本地文件 dwTotalWrite += dwWrite; nRead = pHttpFile->Read(pszBuffer, BUFFER_LENGTH); } delete[]pszBuffer; pszBuffer = NULL; CloseHandle(hFile); } else { delete[]pszBuffer; pszBuffer = NULL; if(pHttpFile != NULL) { pHttpFile->Close(); delete pHttpFile; pHttpFile = NULL; } if(pHttpConnection != NULL) { pHttpConnection->Close(); delete pHttpConnection; pHttpConnection = NULL; } session.Close(); return false; } } catch(...) { delete[]pszBuffer; pszBuffer = NULL; if(pHttpFile != NULL) { pHttpFile->Close(); delete pHttpFile; pHttpFile = NULL; } if(pHttpConnection != NULL) { pHttpConnection->Close(); delete pHttpConnection; pHttpConnection = NULL; } session.Close(); return false; } if(pHttpFile != NULL) pHttpFile->Close(); if(pHttpConnection != NULL) pHttpConnection->Close(); session.Close(); return true; }
///////////////////////////////////////////////////////////////////////////// // DlgURL message handlers void DlgURL::OnOK() { UpdateData(); if (m_url.IsEmpty()) return; m_ok.EnableWindow(0); m_bSafeToClose = FALSE; SetStatus(_T("Connecting to site...")); CString* m_strBuffer = &m_data; CString m_sServer=_T(""); CString m_sObject; INTERNET_PORT m_nPort = INTERNET_DEFAULT_HTTP_PORT; DWORD m_dwServiceType = INTERNET_SERVICE_HTTP; AfxParseURL(m_url, m_dwServiceType, m_sServer, m_sObject, m_nPort); //Create the Internet session handle m_hInternetSession = ::InternetOpen(AfxGetAppName(), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if (m_hInternetSession == NULL){ ThreadError(_T("cannot open internet session")); return; } if (m_bAbort) { OnThreadFinished(1); return; } //Make the connection to the HTTP server m_hHttpConnection = ::InternetConnect(m_hInternetSession, m_sServer, m_nPort , NULL, NULL, m_dwServiceType , 0, (DWORD) this); if (m_hHttpConnection == NULL){ ThreadError(_T("cannot connect to remote server")); return; } if (m_bAbort) { OnThreadFinished(1); return; } //Issue the request to read the file LPCTSTR ppszAcceptTypes[2]; ppszAcceptTypes[0] = _T("*/*"); //We support accepting any mime file type since this is a simple download of a file ppszAcceptTypes[1] = NULL; m_hHttpFile = HttpOpenRequest(m_hHttpConnection, NULL, m_sObject, NULL, NULL, ppszAcceptTypes, INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_KEEP_CONNECTION, (DWORD) this); if (m_hHttpFile == NULL){ ThreadError(_T("Failed in call to HttpOpenRequest")); return; } if (m_bAbort) { OnThreadFinished(1); return; } //Issue the request BOOL bSend = ::HttpSendRequest(m_hHttpFile, NULL, 0, NULL, 0); // Get the length of the file. TCHAR szContentLength[32]; DWORD dwInfoSize = 32; DWORD dwFileSize = 0; if (::HttpQueryInfo(m_hHttpFile, HTTP_QUERY_CONTENT_LENGTH, szContentLength, &dwInfoSize, NULL)){ dwFileSize = (DWORD) _ttol(szContentLength); } //Now do the actual read of the file DWORD dwBytesRead = 0; char szReadBuf[1025]; DWORD dwBytesToRead = 1024; DWORD dwTotalBytesRead = 0; do { if (::InternetReadFile(m_hHttpFile, szReadBuf, dwBytesToRead, &dwBytesRead)){ if (dwBytesRead && !m_bAbort) { //Write the data to file szReadBuf[dwBytesRead]=0; LPTSTR ptr = m_strBuffer->GetBufferSetLength(dwTotalBytesRead + dwBytesRead + 1); memcpy(ptr+dwTotalBytesRead, szReadBuf, dwBytesRead); //Increment the total number of bytes read dwTotalBytesRead += dwBytesRead; m_strBuffer->ReleaseBuffer(dwTotalBytesRead+1); CString s; s.Format(_T("%d/%d"),dwTotalBytesRead,dwFileSize); SetStatus(s); } } else { ThreadError(_T("An error occurred while downloading the file")); return; } } while (dwBytesRead && !m_bAbort); m_size = dwTotalBytesRead; //We're finished OnThreadFinished(0); }
BOOL DownLoad(LPCSTR URL, LPCSTR Path, BOOL& quit, CSocketList& list) { try{ CHttpSocket HttpSocket; CFile DownloadFile; CString strServer,strObject; unsigned short nPort; DWORD dwServiceType; long nLength; const char *pRequestHeader = NULL; SOCKET tmpS = 0; if(!AfxParseURL(URL,dwServiceType,strServer,strObject,nPort)){ //AfxMessageBox("AfxParseURL"); return FALSE; } try{ pRequestHeader = HttpSocket.FormatRequestHeader((LPTSTR)(LPCTSTR)strServer,(LPTSTR)(LPCTSTR)strObject,nLength, nPort); if(!HttpSocket.Socket()) throw 0; tmpS = HttpSocket.GetSocket(); list.AddTail(tmpS); if(quit){ //AfxMessageBox("quit"); return FALSE; } // HttpSocket.SetTimeout(10000,0); if(!HttpSocket.Connect((LPTSTR)(LPCTSTR)strServer,nPort)) throw 1; if(quit) return FALSE; if(!HttpSocket.SendRequest()) throw 1; if(quit) return FALSE; int nLineSize = 0; char szLine[256]; while(nLineSize != -1){ nLineSize = HttpSocket.GetResponseLine(szLine,256); if(quit) return FALSE; } char szValue[30]; BOOL bContLen = TRUE; int nFileSize = -1; if(HttpSocket.GetField("Content-Length",szValue,30)==-1) bContLen = FALSE; else nFileSize = atoi(szValue); if(quit) return FALSE; // int nSvrState = HttpSocket.GetServerState(); int nCompletedSize = 0; if(!DownloadFile.Open(Path, CFile::modeCreate|CFile::modeWrite)) throw 2; if(quit) return FALSE; char pData[1024]; int nReceSize = 0; BOOL first = TRUE; while(!quit){ nReceSize = HttpSocket.Receive(pData,1024); if(quit) return FALSE; if(nReceSize == 0) break; if(nReceSize == -1) throw 3; if(first&&!bContLen){ char* temp = strstr(pData,"\n"); if(!temp) throw 3; DownloadFile.Write(temp+2,nReceSize-(temp+2-pData)); } else DownloadFile.Write(pData,nReceSize); nCompletedSize += nReceSize; first = FALSE; if(bContLen && nCompletedSize>=nFileSize) break; } if(!bContLen && !quit){ long len = (long)DownloadFile.GetLength(); DownloadFile.SetLength(len-7); } DownloadFile.Close(); POSITION pos = list.Find(tmpS); if(pos) list.RemoveAt(pos); HttpSocket.CloseSocket(); } catch(int err){ POSITION pos; switch(err){ case 3: DownloadFile.Close(); case 2: case 1: pos = list.Find(tmpS); if(pos) list.RemoveAt(pos); HttpSocket.CloseSocket(); break; } return FALSE; } return !quit; } catch(...){ #ifdef _DEBUG // AfxMessageBox("BOOL DownLoad(LPCSTR URL, LPCSTR Path, BOOL& quit, CSocketList& list)"); #endif } return FALSE; }
BOOL CHttpDownloadDlg::OnInitDialog() { CString cap; cap = GetResString(IDS_CANCEL); GetDlgItem(IDCANCEL)->SetWindowText(cap); if (!m_strTitle.IsEmpty()) SetWindowText(m_strTitle); //Let the parent class do its thing CDialog::OnInitDialog(); InitWindowStyles(this); //Setup the animation control m_ctrlAnimate.Open(IDR_HTTPDOWNLOAD_ANI); //Validate the URL ASSERT(m_sURLToDownload.GetLength()); //Did you forget to specify the file to download if (!AfxParseURL(m_sURLToDownload, m_dwServiceType, m_sServer, m_sObject, m_nPort)) { //Try sticking "http://" before it m_sURLToDownload = _T("http://") + m_sURLToDownload; if (!AfxParseURL(m_sURLToDownload, m_dwServiceType, m_sServer, m_sObject, m_nPort)) { TRACE(_T("Failed to parse the URL: %s\n"), m_sURLToDownload); EndDialog(IDCANCEL); return TRUE; } } //Check to see if the file we are downloading to exists and if //it does, then ask the user if they were it overwritten // edited: we always want to overwrite old language dlls and server.mets /*CFileStatus fs; ASSERT(m_sFileToDownloadInto.GetLength()); if (CFile::GetStatus(m_sFileToDownloadInto, fs)) { CString sMsg; sMsg.Format(GetResString(IDS_HTTPDOWNLOAD_OK_TO_OVERWRITE), m_sFileToDownloadInto); if (AfxMessageBox(sMsg, MB_YESNO) != IDYES) { TRACE(_T("Failed to confirm file overwrite, download aborted\n")); EndDialog(IDCANCEL); return TRUE; } }*/ //Try and open the file we will download into if (!m_FileToWrite.Open(m_sFileToDownloadInto, CFile::modeCreate | CFile::modeWrite | CFile::shareDenyWrite)) { TRACE(_T("Failed to open the file to download into, Error:%d\n"), GetLastError()); CString sError; sError.Format(_T("%d"), ::GetLastError()); CString sMsg; sMsg.Format(GetResString(IDS_HTTPDOWNLOAD_FAIL_FILE_OPEN), sError); AfxMessageBox(sMsg); EndDialog(IDCANCEL); return TRUE; } //Pull out just the filename component int nSlash = m_sObject.ReverseFind(_T('/')); if (nSlash == -1) nSlash = m_sObject.ReverseFind(_T('\\')); if (nSlash != -1 && m_sObject.GetLength() > 1) m_sFilename = m_sObject.Right(m_sObject.GetLength() - nSlash - 1); else m_sFilename = m_sObject; //Set the file status text CString sFileStatus; ASSERT(m_sObject.GetLength()); ASSERT(m_sServer.GetLength()); sFileStatus.Format(GetResString(IDS_HTTPDOWNLOAD_FILESTATUS), m_sFilename, m_sServer); m_ctrlFileStatus.SetWindowText(sFileStatus); // set labels SetDlgItemText(IDC_TIMELEFTTEXT,GetResString(IDS_ESTTIMELEFT)); SetDlgItemText(IDC_TRANSFER_RATE_LABEL,GetResString(IDS_TRANSFER_RATE_LABEL)); //Spin off the background thread which will do the actual downloading m_pThread = AfxBeginThread(_DownloadThread, this, THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED); if (m_pThread == NULL) { TRACE(_T("Failed to create download thread, dialog is aborting\n")); EndDialog(IDCANCEL); return TRUE; } m_pThread->m_bAutoDelete = FALSE; m_pThread->ResumeThread(); return TRUE; }
int CHttpClient::ExecuteRequest(LPCTSTR strMethod, LPCTSTR strUrl, LPCTSTR strPostData, string &strResponse) { CString strServer; CString strObject; DWORD dwServiceType; INTERNET_PORT nPort; strResponse = ""; AfxParseURL(strUrl, dwServiceType, strServer, strObject, nPort); if(AFX_INET_SERVICE_HTTP != dwServiceType && AFX_INET_SERVICE_HTTPS != dwServiceType) { return FAILURE; } try { m_pConnection = m_pSession->GetHttpConnection(strServer, dwServiceType == AFX_INET_SERVICE_HTTP ? NORMAL_CONNECT : SECURE_CONNECT, nPort); m_pFile = m_pConnection->OpenRequest(strMethod, strObject, NULL, 1, NULL, NULL, (dwServiceType == AFX_INET_SERVICE_HTTP ? NORMAL_REQUEST : SECURE_REQUEST)); //DWORD dwFlags; //m_pFile->QueryOption(INTERNET_OPTION_SECURITY_FLAGS, dwFlags); //dwFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA; ////set web server option //m_pFile->SetOption(INTERNET_OPTION_SECURITY_FLAGS, dwFlags); m_pFile->AddRequestHeaders(_T("Accept: *,*/*")); m_pFile->AddRequestHeaders(_T("Accept-Language: zh-cn")); m_pFile->AddRequestHeaders(_T("Content-Type: application/x-www-form-urlencoded")); m_pFile->AddRequestHeaders(_T("Accept-Encoding: gzip, deflate")); m_pFile->AddRequestHeaders(_T("User-Agent: VersionClient")); m_pFile->SendRequest(NULL, 0, (LPVOID)(LPCTSTR)strPostData, strPostData == NULL ? 0 : _tcslen(strPostData)); char szChars[BUFFER_SIZE + 1] = {0}; string strRawResponse = ""; UINT nReaded = 0; while ((nReaded = m_pFile->Read((void*)szChars, BUFFER_SIZE)) > 0) { szChars[nReaded] = '\0'; strRawResponse += szChars; memset(szChars, 0, BUFFER_SIZE + 1); } int unicodeLen = MultiByteToWideChar(CP_UTF8, 0, strRawResponse.c_str(), -1, NULL, 0); WCHAR *pUnicode = new WCHAR[unicodeLen + 1]; memset(pUnicode,0,(unicodeLen+1)*sizeof(wchar_t)); MultiByteToWideChar(CP_UTF8,0,strRawResponse.c_str(),-1, pUnicode,unicodeLen); CString cs(pUnicode); CStringA csA(cs.GetBuffer(0)); cs.ReleaseBuffer(); delete []pUnicode; pUnicode = NULL; strResponse = csA; Clear(); } catch (CInternetException* e) { Clear(); DWORD dwErrorCode = e->m_dwError; e->Delete(); DWORD dwError = GetLastError(); CStringA strError; strError.Format("dwError = %d", dwError, 0); strResponse = strError; if (ERROR_INTERNET_TIMEOUT == dwErrorCode) { return OUTTIME; } else { return FAILURE; } } return SUCCESS; }