bool CLoginDialog::pinReminder(){ CString username, email; int country=((CComboBox*) GetDlgItem(IDC_COUNTRY))->GetCurSel(); std::string userPhone=countries[country][1]; userPhone.erase(std::find(userPhone.begin(), userPhone.end(), '+')); userPhone.erase(std::find(userPhone.begin(), userPhone.end(), '-')); GetDlgItemText(IDC_PHONE,username); username=(CString)userPhone.c_str()+username; GetDlgItemText(IDC_EMAIL,email); std::string header = "/oneworld/forgotpin?number="; header+=(CT2CA)username; header+="&email="; header+=(CT2CA)email; CInternetSession session; CHttpConnection *pConnection = session.GetHttpConnection(_T("89.163.142.253")); char result[500]; CString request(header.c_str()); CHttpFile *pFile = pConnection->OpenRequest(1,request); if(!pFile->SendRequest()) return false; //pFile->QueryInfo(HTTP_QUERY_FLAG_REQUEST_HEADERS,result,(LPDWORD)500); #ifdef _DEBUG pFile->Read((void*)result,500); _cprintf("%s",result); #endif return true; }
BOOL CMainFrame::DonwLoadFile(PSTR pURL, LPSTR SaveAsFilePath) { CInternetSession session; CHttpConnection* pServer = NULL; CHttpFile * pHttpFile = NULL; CString strServerName; //去掉http:// CString strObject; INTERNET_PORT nPort; DWORD dwServiceType; DWORD dwHttpRequestFlags = INTERNET_FLAG_NO_AUTO_REDIRECT; //请求标志 const TCHAR szHeaders[]=_T("Accept: text/*\r\nUser-Agent:HttpClient\r\n"); BOOL OK=AfxParseURL( pURL, dwServiceType, strServerName, strObject, nPort ); pServer = session.GetHttpConnection(strServerName, nPort); //获得服务器名 pHttpFile = pServer-> OpenRequest( CHttpConnection::HTTP_VERB_GET, strObject, NULL, 1, NULL, NULL, dwHttpRequestFlags); pHttpFile->AddRequestHeaders(szHeaders); try { pHttpFile->SendRequest(); //发送请求 } catch (CInternetException* IE) { return false; } CStdioFile f; if( !f.Open( SaveAsFilePath, CFile::modeCreate | CFile::modeWrite | CFile::typeBinary ) ) { return false; } TCHAR szBuf[1024]; int length=0; long a=pHttpFile->GetLength(); while (length=pHttpFile->Read(szBuf, 1023)) f.Write(szBuf,length); f.Close(); pHttpFile ->Close(); pServer ->Close(); if (pHttpFile != NULL) delete pHttpFile; if (pServer != NULL) delete pServer; session.Close(); return true; }
int CXCCRA2MapUpdaterApp::download_update(string link, string fname) { int error = 0; CInternetSession is; CHttpFile* f = reinterpret_cast<CHttpFile*>(is.OpenURL(link.c_str(), INTERNET_FLAG_TRANSFER_BINARY)); if (!f) error = 1; else { Cvirtual_file h; DWORD status; if (!f->QueryInfoStatusCode(status)) error = 2; else if (status != 200) error = 3; else { int total_size = f->Seek(0, CFile::end); f->Seek(0, CFile::begin); Cdownload_dlg dlg; dlg.set(link, fname, total_size); dlg.Create(Cdownload_dlg::IDD, NULL); dlg.EnableWindow(false); Cvirtual_binary t; while (!error) { int cb_p = min<int>(f->GetLength(), 1 << 10); if (!cb_p) break; f->Read(t.write_start(cb_p), cb_p); h.write(t); dlg.set_size(h.size()); dlg.UpdateWindow(); } h.compact(); Cxif_key k; if (k.load_key(h.data(), h.size())) error = 5; else { for (t_xif_key_map::const_iterator ki = k.m_keys.begin(); ki != k.m_keys.end(); ki++) { if (error) break; const Cxif_key& l = ki->second; string fext = boost::to_lower_copy(Cfname(l.get_value_string(vi_fname)).get_fext()); if (fext != ".mmx" && (fext != ".yro") || !Cfname(xcc_dirs::get_exe(game_ra2_yr)).exists()) continue; if (file32_write(Cfname(fname).get_path() + l.get_value_string(vi_fname), l.get_value(vi_fdata).get_data(), l.get_value(vi_fdata).get_size())) error = 6; } } dlg.DestroyWindow(); } f->Close(); } return error; }
CString GetPageDirect(CString rAddress) { CString szResult; DWORD dwRet = 0; // HTTP返回码 CString strServerName, strObject; DWORD dwSvrType; INTERNET_PORT nPort; const TCHAR szHeaders[] = _T("Accept: text/*\r\nUser-Agent: CInternetThread\r\n"); AfxParseURL(rAddress, dwSvrType, strServerName, strObject, nPort); CInternetSession session("MySessionDirect"); CHttpConnection* pServer = NULL; CHttpFile* pFile = NULL; try { pServer = session.GetHttpConnection(strServerName, nPort); pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject); pFile->AddRequestHeaders(szHeaders); pFile->SendRequest(); pFile->QueryInfoStatusCode(dwRet); if (dwRet < 400) { char szBuff[1024]; UINT nRead = pFile->Read(szBuff, 1023); while (nRead > 0) { szBuff[nRead] = '\0'; szResult.Append(szBuff); nRead = pFile->Read(szBuff, 1023); } } delete pFile; delete pServer; } catch (CInternetException* pEx) { //uiResult = 0; } session.Close(); return szResult; }
UINT CGetAccountInfoRequest::ProcessResponse(CHttpFile& pHttpFile) { #ifdef ARTSTORE return 1; #else //Take the HttpFile and parse it. UINT nFileLength = pHttpFile.GetLength(); CString strBuffer; CString strSearch; CString strList; LPSTR b = strBuffer.GetBuffer(nFileLength); pHttpFile.Read(b, nFileLength); strBuffer.ReleaseBuffer(); CBasicRequestInfo::ProcessResponse(strBuffer); UINT nRet = atoi((LPCTSTR)GetStatusCode()); if(nRet == 0) //success { CString strSearch; strSearch = "Last="; ParseFileForValue(strBuffer, strSearch, GetCustLastName()); strSearch = "First="; ParseFileForValue(strBuffer, strSearch, GetCustFirstName()); strSearch = "Street1="; ParseFileForValue(strBuffer, strSearch, GetStreet1()); strSearch = "Street2="; ParseFileForValue(strBuffer, strSearch, GetStreet2()); strSearch = "City="; ParseFileForValue(strBuffer, strSearch, GetCity()); strSearch = "State="; ParseFileForValue(strBuffer, strSearch, GetState()); strSearch = "Country="; ParseFileForValue(strBuffer, strSearch, GetCountry()); strSearch = "ZipCode="; ParseFileForValue(strBuffer, strSearch, GetZipCode()); strSearch = "EMail="; ParseFileForValue(strBuffer, strSearch, GetEMail()); strSearch = "Phone="; ParseFileForValue(strBuffer, strSearch, GetPhone()); } return nRet; #endif }
void Conference::LoadList(){ CListCtrl *conf= (CListCtrl*)GetDlgItem(IDC_CONFLIST); conf->DeleteAllItems(); std::string header = "/oneworld/conf_list?api_token="; header+=((CmicrosipDlg*)GetParent())->getToken(); CInternetSession session; CHttpConnection *pConnection = session.GetHttpConnection(_T("89.163.142.253")); char result[500]; CString request(header.c_str()); CHttpFile *pFile = pConnection->OpenRequest(1,request); if(!pFile->SendRequest()) return; pFile->Read((void*)result,500); char* status = strchr(result,']'); //checking if data is receive and is parseable char* eom = strchr(result,'}'); #ifdef _DEBUG _cprintf("Size: %p, %p, %d\n",result, status, (status-result)); #endif if(status==NULL) result[eom-result+1]='\0'; else if(status - result < 4998) result[status - result +2]='\0'; #ifdef _DEBUG _cprintf("Result: %s\n",result); #endif cJSON *root = cJSON_Parse(result); cJSON *msg = cJSON_GetObjectItem(root,"msg"); if((status==NULL && msg == NULL) || status-result >= 4999 ) return; else if(status==NULL) return; cJSON *data = cJSON_GetObjectItem(root,"data"); int size=cJSON_GetArraySize(root); #ifdef _DEBUG _cprintf("Size: %d\n",size); #endif size=cJSON_GetArraySize(data); #ifdef _DEBUG _cprintf("Size: %d\n",size); #endif for(int i=0;i<size;i++){ cJSON* item= cJSON_GetArrayItem(data,i); CString confNum(cJSON_GetObjectItem(item,"confno")->valuestring); CString pin(cJSON_GetObjectItem(item,"pin")->valuestring); #ifdef _DEBUG _cprintf("Item: %s\n",(CT2CA)confNum); _cprintf("Pin: %s\n",(CT2CA)pin); #endif int index = conf->InsertItem(i, confNum); conf->SetItemText(index, 1, pin); //conf->SetItemData(i, &confNum); } }
bool CLoginDialog::registration(){ CString phone, name, email; int country=((CComboBox*) GetDlgItem(IDC_COUNTRY))->GetCurSel(); GetDlgItemText(IDC_PHONE,phone); GetDlgItemText(IDC_NAME,name); GetDlgItemText(IDC_EMAIL,email); std::string header = "/oneworld/webreg?country="; header+=countries[country][2]; header+="&number="; header+=(CT2CA)phone; header+="&name="; header+=(CT2CA)name; header+="&email="; header+=(CT2CA)email; header+="&countrycode="; header+=countries[country][2]; CInternetSession session; CHttpConnection *pConnection = session.GetHttpConnection(_T("89.163.142.253")); char result[500]; CString request(header.c_str()); CHttpFile *pFile = pConnection->OpenRequest(1,request); if(!pFile->SendRequest()) return false; //pFile->QueryInfo(HTTP_QUERY_FLAG_REQUEST_HEADERS,result,(LPDWORD)500); #ifdef _DEBUG pFile->Read((void*)result,500); _cprintf("%s",result); #endif CString rest(result); int start=rest.Find(_T("success\":\"")); if(start<0) return false; start+=((CString)_T("success\":\"")).GetLength(); int end=rest.Find(_T("\""),start); if(end<0) return false; CString success=rest.Mid(start, end-start); #ifdef _DEBUG _cprintf("%s",(CT2CA)success); _cprintf("%s",result); #endif start=rest.Find(_T("msg\":\"")); start+=((CString)_T("msg\":\"")).GetLength(); end=rest.Find(_T("\""),start); CString msg=rest.Mid(start, end-start); SetDlgItemText(IDC_LOGTEXT,msg); Sleep(2000); return true; }
int CXCCRA2MapUpdaterApp::update() { int error = 0; try { CWaitCursor wait; CInternetSession is; CHttpFile* f = reinterpret_cast<CHttpFile*>(is.OpenURL("http://xccu.sourceforge.net/ra2_maps/official.ucf")); if (!f) error = 1; else { string s; while (1) { int cb_p = f->GetLength(); if (!cb_p) break; char* p = new char[cb_p + 1]; f->Read(p, cb_p); p[cb_p] = 0; s += p; delete[] p; } f->Close(); Cvirtual_tfile f; f.load_data(Cvirtual_binary(s.c_str(), s.length())); while (!f.eof()) { Cmulti_line l = f.read_line(); Cfname fname = xcc_dirs::get_dir(game_ra2) + l.get_next_line('=') + ".mmx"; if (!fname.exists()) { string version = l.get_next_line(','); string link = l.get_next_line(','); error = download_update(link, fname); if (error) { delete_file(fname); MessageBox(NULL, "Error retrieving update.", NULL, MB_ICONERROR); error = 0; } } } } } catch (CInternetException*) { error = 1; } if (error) MessageBox(NULL, "Error querying for update.", NULL, MB_ICONERROR); return error; }
BOOL CAutoUpdateDlg::DownloadFile(LPCTSTR lpURL,LPCTSTR lpDestFile) { CFile cUdpFile; if(!cUdpFile.Open(lpDestFile,CFile::modeCreate|CFile::modeWrite|CFile::typeBinary|CFile::shareDenyWrite)) return FALSE; BOOL bResult = FALSE; CInternetSession sessionDownload; try { CHttpFile* pFile = (CHttpFile*)sessionDownload.OpenURL(lpURL,1,INTERNET_FLAG_TRANSFER_BINARY|INTERNET_FLAG_RELOAD|INTERNET_FLAG_DONT_CACHE); CString query = _T(""); pFile->QueryInfo(HTTP_QUERY_CONTENT_LENGTH,query); long file_len=_ttol(query); m_dwTotalSize = file_len; PostMessage(WM_POSMESSAGE,0,0); DWORD dwStatus; if (pFile->QueryInfoStatusCode(dwStatus)) { if (dwStatus == 200) { pFile->SetReadBufferSize(10240); if (TRUE) { DWORD dwLen = 0; char buf[BLOCKSIZE]; while (TRUE) { DWORD dwTemp = pFile->Read(buf,BLOCKSIZE); if (dwTemp) { cUdpFile.Write(buf,dwTemp); } m_dwDownloadedSize += dwTemp; PostMessage(WM_POSMESSAGE,0,0); if (dwTemp < BLOCKSIZE) { break; } } } } } pFile->Close(); bResult = TRUE; } catch(CInternetException* pException) { pException->Delete(); return bResult; } sessionDownload.Close(); cUdpFile.Close(); return bResult; }
CString C51JobWebPost::GeHttptFile(const char *url) { CString szContent; char strProxyList[MAX_PATH], strUsername[64], strPassword[64]; //in this case "proxya" is the proxy server name, "8080" is its port strcpy(strProxyList, "125.41.181.59:8080"); strcpy(strUsername, "myusername"); strcpy(strPassword, "mypassword"); DWORD dwServiceType = AFX_INET_SERVICE_HTTP; CString szServer, szObject; INTERNET_PORT nPort; AfxParseURL(url, dwServiceType, szServer, szObject, nPort); CInternetSession mysession; CHttpConnection* pConnection; CHttpFile* pHttpFile; INTERNET_PROXY_INFO proxyinfo; proxyinfo.dwAccessType = INTERNET_OPEN_TYPE_PROXY; proxyinfo.lpszProxy = strProxyList; proxyinfo.lpszProxyBypass = NULL; mysession.SetOption(INTERNET_OPTION_PROXY, (LPVOID)&proxyinfo, sizeof(INTERNET_PROXY_INFO)); pConnection = mysession.GetHttpConnection("125.41.181.59", INTERNET_FLAG_KEEP_CONNECTION, 8080, NULL, NULL); pHttpFile = pConnection->OpenRequest("GET",url, NULL, 0, NULL, NULL, INTERNET_FLAG_KEEP_CONNECTION); //here for proxy //pHttpFile->SetOption(INTERNET_OPTION_PROXY_USERNAME, strUsername, strlen(strUsername)+1); //pHttpFile->SetOption(INTERNET_OPTION_PROXY_PASSWORD, strPassword, strlen(strPassword)+1); pHttpFile->SendRequest(NULL); DWORD nFileSize = pHttpFile->GetLength(); LPSTR rbuf = szContent.GetBuffer(nFileSize); UINT uBytesRead = pHttpFile->Read(rbuf, nFileSize); szContent.ReleaseBuffer(); pHttpFile->Close(); delete pHttpFile; pConnection->Close(); delete pConnection; mysession.Close(); return szContent; }
bool CDlgView::DownLoadFile(const string&UrpPath ,const string& strFilePath) { CInternetSession session; std::string strHtml; try { CHttpFile* pfile = (CHttpFile*)session.OpenURL(UrpPath.c_str(),1,INTERNET_FLAG_TRANSFER_ASCII|INTERNET_FLAG_RELOAD,NULL,0); DWORD dwStatusCode; pfile->QueryInfoStatusCode(dwStatusCode); if(dwStatusCode == HTTP_STATUS_OK) { char strBuff[1025] = {0}; while ((pfile->Read((void*)strBuff, 1024)) > 0) { strHtml += strBuff; } } else { return false; } pfile->Close(); delete pfile; session.Close(); } catch (CException* e) { e;//消除警告 return false; } if (!strHtml.empty()) { ofstream outfile(strFilePath); if (!outfile.is_open()) { return false; } outfile<<strHtml; outfile.close(); } return true; }
void Conference::OnDelete() { CListCtrl *list= (CListCtrl*)GetDlgItem(IDC_CONFLIST); POSITION pos = list->GetFirstSelectedItemPosition(); CString confNum; if (pos) { int i = list->GetNextSelectedItem(pos); //Call *pCall = (Call *) list->GetItemData(i); confNum=list->GetItemText(i,0); } if(confNum.GetLength()==0) return; std::string header = "/oneworld/conf_del?api_token="; header+=((CmicrosipDlg*)GetParent())->getToken(); header+="&confno="; header+=(CT2CA)confNum; #ifdef _DEBUG _cprintf("Request: %s\n",header); #endif CInternetSession session; CHttpConnection *pConnection = session.GetHttpConnection(_T("89.163.142.253")); char result[500]; CString request(header.c_str()); CHttpFile *pFile = pConnection->OpenRequest(1,request); if(!pFile->SendRequest()) return; pFile->Read((void*)result,500); char* status = strchr(result,']'); //checking if data is receive and is parseable char* eom = strchr(result,'}'); #ifdef _DEBUG _cprintf("Size: %p, %p, %d\n",result, status, (status-result)); #endif if(status==NULL) result[eom-result+1]='\0'; else if(status - result < 498) result[status - result +2]='\0'; #ifdef _DEBUG _cprintf("Result: %s\n",result); #endif LoadList(); }
Update_Status UpdateChecker::isUpdateAvailable(const Version& currentVersion) { Update_Status updateAvailable = UPDATER_LATEST_STABLE; try { CInternetSession internet; CHttpFile* versionFile = (CHttpFile*) internet.OpenURL(versionFileURL, 1, INTERNET_FLAG_TRANSFER_ASCII | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_RELOAD, NULL, 0); if (versionFile) { CString latestVersionStr; char buffer[101]; UINT br = 0; while ((br = versionFile->Read(buffer, 50)) > 0) { buffer[br] = '\0'; latestVersionStr += buffer; } if (!parseVersion(latestVersionStr)) { updateAvailable = UPDATER_ERROR; } else { int comp = compareVersion(currentVersion, latestVersion); if (comp < 0) { updateAvailable = UPDATER_UPDATE_AVAILABLE; } else if (comp > 0) { updateAvailable = UPDATER_NEWER_VERSION; } } delete versionFile; } else { updateAvailable = UPDATER_ERROR; } } catch (CInternetException* pEx) { updateAvailable = UPDATER_ERROR; pEx->Delete(); } return updateAvailable; }
/* * Connect to the Tally over a specific port and get all the companies */ BOOL CTallyExporterDlg::GetCompanyListFromTallyServer(int port, CompanyListResponse& companyListResponseRef) { CInternetSession session(_T("My Session")); CHttpConnection* pServer = NULL; CHttpFile* pFile = NULL; try { CString strServerName; DWORD dwRet = 0; CString strParam = "<ENVELOPE><HEADER><TALLYREQUEST>Export Data</TALLYREQUEST></HEADER><BODY><EXPORTDATA><REQUESTDESC><REPORTNAME>List of Companies</REPORTNAME></REQUESTDESC></EXPORTDATA></BODY></ENVELOPE>"; CString strHeaders = _T("Content-Type: application/x-www-form-urlencoded;Accept-Encoding: gzip,deflate"); CString acceptedTypes[] = {_T("text/html")}; pServer = session.GetHttpConnection(_T("localhost"),NULL, port, NULL, NULL); pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST, _T(""), NULL,1,(LPCTSTR*)acceptedTypes,NULL,INTERNET_FLAG_EXISTING_CONNECT); pFile->SendRequest(strHeaders, (LPVOID)(LPCTSTR)strParam, strParam.GetLength()); pFile->QueryInfoStatusCode(dwRet); if (dwRet == HTTP_STATUS_OK) { CHAR szBuff[1024]; while (pFile->Read(szBuff, 1024) > 0) { printf_s("%1023s", szBuff); } GetCompanyListFromCSVResponse(companyListResponseRef, szBuff); } else { //Do something as server is not sending response as expected. } delete pFile; delete pServer; } catch (CInternetException* pEx) { //catch errors from WinInet TCHAR pszError[64]; pEx->GetErrorMessage(pszError, 64); _tprintf_s(_T("%63s"), pszError); } session.Close(); return false; }
void Conference::OnBnClickedConfsubmit() { std::string header = "/oneworld/conf_create?api_token="; header+=((CmicrosipDlg*)GetParent())->getToken(); header+="&pin="; CString pinNum; GetDlgItemText(IDC_CONFPIN,pinNum); header+=(CT2CA)pinNum; header+="&length=0"; CInternetSession session; CHttpConnection *pConnection = session.GetHttpConnection(_T("89.163.142.253")); char result[500]; CString request(header.c_str()); CHttpFile *pFile = pConnection->OpenRequest(1,request); if(!pFile->SendRequest()) return; pFile->Read((void*)result,500); char* status = strchr(result,']'); //checking if data is receive and is parseable char* eom = strchr(result,'}'); #ifdef _DEBUG _cprintf("Size: %p, %p, %d\n",result, status, (status-result)); #endif if(status==NULL) result[eom-result+1]='\0'; else if(status - result < 498) result[status - result +2]='\0'; #ifdef _DEBUG _cprintf("Result: %s\n",result); #endif cJSON *root = cJSON_Parse(result); cJSON *success = cJSON_GetObjectItem(root,"success"); #ifdef _DEBUG _cprintf("Success: %s\n",success->valuestring); #endif LoadList(); }
// Downloads the file at the given URL and returns the size of that file. CString GetHttpFile(CInternetSession& session, const CString& strUrl) { CString strResult; // Reads data from an HTTP server. CHttpFile* pHttpFile = NULL; try { // Open URL. pHttpFile = (CHttpFile*)session.OpenURL(strUrl, 1, INTERNET_FLAG_TRANSFER_ASCII | INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE); // Read the file. if(pHttpFile != NULL) { UINT uiBytesRead; do { char chBuffer[10000]; uiBytesRead = pHttpFile->Read(chBuffer, sizeof(chBuffer)); strResult += chBuffer; } while (uiBytesRead > 0); } } catch (CInternetException) { // TODO: Handle exception } // Clean up and return. delete pHttpFile; return strResult; }
static DWORD WINAPI URLGetAsyncThread( LPVOID lpParam ) { URLGetAsyncData *data = (URLGetAsyncData *)lpParam; if (!data->url.IsEmpty()) { CInternetSession session; try { CHttpFile* pFile; pFile = (CHttpFile*)session.OpenURL(data->url, NULL, INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE); if (pFile) { pFile->QueryInfoStatusCode(data->statusCode); CStringA buf; char pBuf[256]; int i; do { i = pFile->Read(pBuf,255); pBuf[i] = 0; data->body.AppendFormat("%s",pBuf); } while (i>0); //-- pFile->QueryInfo( HTTP_QUERY_RAW_HEADERS_CRLF, data->headers ); pFile->Close(); } session.Close(); } catch (CInternetException *e) { data->statusCode = 0; } } if (data->message) { SendMessage(data->hWnd,data->message,(WPARAM)data,0); } delete data; return 0; }
UINT CUpdateAccountRequest::ProcessResponse(CHttpFile& pHttpFile) { #ifdef ARTSTORE return 1; #else //Take the HttpFile and parse it. UINT uRet = 1; UINT nFileLength = pHttpFile.GetLength(); CString strBuffer; CString strSearch; CString strList; LPSTR b = strBuffer.GetBuffer(nFileLength); pHttpFile.Read(b, nFileLength); strBuffer.ReleaseBuffer(); uRet = CBasicRequestInfo::ProcessResponse(strBuffer); #if 0 if(uRet == 0) { if(GetNewPassword() != "") { if(GetNewPassword() != GetPassword()) { LPSTR s = GetNewPassword().GetBuffer(255); //WritePrivateProfileString("Server Account", "Password", s, "Pmw.ini"); GET_PMWAPP()->WritePrivateProfileString(SECTION_ServerAccount, ENTRY_ServerPassword, s, GET_PMWAPP()->main_ini); GetNewPassword().ReleaseBuffer(); } } } #endif return uRet; #endif }
CHAR* WebFetcher::GetHttp(LPCSTR lpServerName) { CInternetSession sess; // 统一以二进制方式下载 DWORD dwFlag = INTERNET_FLAG_TRANSFER_BINARY|INTERNET_FLAG_DONT_CACHE|INTERNET_FLAG_RELOAD; CHttpFile *pF = (CHttpFile*)sess.OpenURL(lpServerName, 1, dwFlag); ASSERT(pF); if (!pF) { AfxThrowInternetException(1); } // 得到文件大小 CString str; pF->QueryInfo(HTTP_QUERY_CONTENT_LENGTH, str); int nFileSize = _ttoi(str); char *p = new char[nFileSize]; while (true) { // 每次下载8Kb int n = pF->Read(p, (nFileSize < 8192) ? nFileSize : 8192); if (n <= 0) { break; } p += n; nFileSize -= n; } //delete[] p; pF->Close(); delete pF; return p; }
int main(int argc, char* argv[]) { ShowBanner(); if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0)) { cerr << _T("MFC Failed to initialize.\n"); return 1; } if (argc < 2 || !ParseOptions(argc, argv) || pszURL == NULL) ShowUsage(); int nRetCode = 0; CTearSession session(_T("TEAR - MFC Sample App"), dwAccessType); CHttpConnection* pServer = NULL; CHttpFile* pFile = NULL; try { // check to see if this is a reasonable URL CString strServerName; CString strObject; INTERNET_PORT nPort; DWORD dwServiceType; if (!AfxParseURL(pszURL, dwServiceType, strServerName, strObject, nPort) || dwServiceType != INTERNET_SERVICE_HTTP) { cerr << _T("Error: can only use URLs beginning with http://") << endl; ThrowTearException(1); } if (bProgressMode) { cerr << _T("Opening Internet..."); VERIFY(session.EnableStatusCallback(TRUE)); } pServer = session.GetHttpConnection(strServerName, nPort); pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject, NULL, 1, NULL, NULL, dwHttpRequestFlags); pFile->AddRequestHeaders(szHeaders); pFile->SendRequest(); DWORD dwRet; pFile->QueryInfoStatusCode(dwRet); // if access was denied, prompt the user for the password if (dwRet == HTTP_STATUS_DENIED) { DWORD dwPrompt; dwPrompt = pFile->ErrorDlg(NULL, ERROR_INTERNET_INCORRECT_PASSWORD, FLAGS_ERROR_UI_FLAGS_GENERATE_DATA | FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS, NULL); // if the user cancelled the dialog, bail out if (dwPrompt != ERROR_INTERNET_FORCE_RETRY) { cerr << _T("Access denied: Invalid password\n"); ThrowTearException(1); } pFile->SendRequest(); pFile->QueryInfoStatusCode(dwRet); } CString strNewLocation; pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, strNewLocation); // were we redirected? // these response status codes come from WININET.H if (dwRet == HTTP_STATUS_MOVED || dwRet == HTTP_STATUS_REDIRECT || dwRet == HTTP_STATUS_REDIRECT_METHOD) { CString strNewLocation; pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, strNewLocation); int nPlace = strNewLocation.Find(_T("Location: ")); if (nPlace == -1) { cerr << _T("Error: Site redirects with no new location") << endl; ThrowTearException(2); } strNewLocation = strNewLocation.Mid(nPlace + 10); nPlace = strNewLocation.Find('\n'); if (nPlace > 0) strNewLocation = strNewLocation.Left(nPlace); // close up the redirected site pFile->Close(); delete pFile; pServer->Close(); delete pServer; if (bProgressMode) { cerr << _T("Caution: redirected to "); cerr << (LPCTSTR) strNewLocation << endl; } // figure out what the old place was if (!AfxParseURL(strNewLocation, dwServiceType, strServerName, strObject, nPort)) { cerr << _T("Error: the redirected URL could not be parsed.") << endl; ThrowTearException(2); } if (dwServiceType != INTERNET_SERVICE_HTTP) { cerr << _T("Error: the redirected URL does not reference a HTTP resource.") << endl; ThrowTearException(2); } // try again at the new location pServer = session.GetHttpConnection(strServerName, nPort); pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject, NULL, 1, NULL, NULL, dwHttpRequestFlags); pFile->AddRequestHeaders(szHeaders); pFile->SendRequest(); pFile->QueryInfoStatusCode(dwRet); if (dwRet != HTTP_STATUS_OK) { cerr << _T("Error: Got status code ") << dwRet << endl; ThrowTearException(2); } } cerr << _T("Status Code is ") << dwRet << endl; TCHAR sz[1024]; while (pFile->ReadString(sz, 1023)) { if (bStripMode) StripTags(sz); cout << sz; } // NOTE: Since HTTP servers normally spit back plain text, the // above code (which reads line by line) is just fine. However, // other data sources (eg, FTP servers) might provide binary data // which should be handled a buffer at a time, like this: #if 0 while (nRead > 0) { sz[nRead] = '\0'; if (bStripMode) StripTags(sz); cout << sz; nRead = pFile->Read(sz, 1023); } #endif pFile->Close(); pServer->Close(); } catch (CInternetException* pEx) { // catch errors from WinINet TCHAR szErr[1024]; pEx->GetErrorMessage(szErr, 1024); cerr << _T("Error: (") << pEx->m_dwError << _T(") "); cerr << szErr << endl; nRetCode = 2; pEx->Delete(); } catch (CTearException* pEx) { // catch things wrong with parameters, etc nRetCode = pEx->m_nErrorCode; TRACE1("Error: Exiting with CTearException(%d)\n", nRetCode); pEx->Delete(); } if (pFile != NULL) delete pFile; if (pServer != NULL) delete pServer; session.Close(); return nRetCode; }
bool CVBFile::getFile(TCHAR *url, TCHAR *location) { bool bRet = true; CInternetSession sess ; CHttpFile *phttpFile; CString Status; CFile lfile; char *buf=NULL; char *pbuf=NULL; DWORD dwFlag = INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_RELOAD ; try { //here, should think of proxy SetOption. // //INTERNET_OPTION_PROXY //INTERNET_OPTION_PROXY_PASSWORD //INTERNET_OPTION_PROXY_USERNAME phttpFile = (CHttpFile*)sess.OpenURL(url, 1, dwFlag); VERIFY(phttpFile); phttpFile->QueryInfo(HTTP_QUERY_STATUS_CODE, Status) ; if (Status != _T("200")) { bRet=false; phttpFile->Close(); delete phttpFile ; goto lExit; } phttpFile->QueryInfo(HTTP_QUERY_CONTENT_LENGTH, Status) ; // file's length long filelen = _ttol(Status); long totalLen = filelen; buf = new char[filelen+1]; pbuf = buf; ::ZeroMemory(buf, filelen+1); while(true) { int n = phttpFile->Read (buf, (filelen < 8192) ? filelen : 8192) ; if (n <= 0) break ; buf += n ; filelen -= n ; } phttpFile->Close(); delete phttpFile; lfile.Open(location, CFile::modeCreate | CFile::modeWrite); lfile.Write((void*)pbuf, totalLen); lfile.Close(); } catch(...) { bRet = false; goto lExit; } lExit: delete pbuf; return bRet; }
CHAR* WebFetcher::GetHttp(LPCSTR lpServerName) { // start download file char *pBuf = NULL ; int nBufLen = 0 ; TRY { // connection CInternetSession sess ; sess.SetOption (INTERNET_OPTION_CONNECT_TIMEOUT, 30 * 1000) ; sess.SetOption (INTERNET_OPTION_CONNECT_BACKOFF, 1000) ; sess.SetOption (INTERNET_OPTION_CONNECT_RETRIES, 1) ; DWORD dwFlag = INTERNET_FLAG_TRANSFER_BINARY|INTERNET_FLAG_DONT_CACHE|INTERNET_FLAG_RELOAD ; CHttpFile * pF = (CHttpFile*)sess.OpenURL(lpServerName, 1, dwFlag); ASSERT(pF); if (!pF) {AfxThrowInternetException(1);} // connection status CString str ; pF->QueryInfo (HTTP_QUERY_STATUS_CODE, str) ; // Proxy Authentication Required if (str == _T("407")) { CString strUsername, strPassword ; // pPara->pThis->df_Notify (GetMsg_ProxyValidate(), &WM_DLF_PROXY_VALIDATE(&lpServerName, &strUsername, &strPassword)) ; pF->SetOption (INTERNET_OPTION_PROXY_USERNAME, (VOID*)(LPCTSTR)strUsername, strUsername.GetLength()) ; pF->SetOption (INTERNET_OPTION_PROXY_PASSWORD, (VOID*)(LPCTSTR)strPassword, strPassword.GetLength()) ; pF->SendRequest (NULL) ; } pF->QueryInfo (HTTP_QUERY_STATUS_CODE, str) ; if (str != _T("200")) { pF->Close() ; delete pF ; AfxThrowInternetException(1); } // confirm update pF->QueryInfo (HTTP_QUERY_LAST_MODIFIED, str) ; /* if (!pPara->pThis->df_Notify (GetMsg_CheckTime(), &WM_DLF_CHECKTIME(&lpServerName, &str))) { pF->Close() ; delete pF ; AfxThrowInternetException(1); } */ // start download pF->QueryInfo (HTTP_QUERY_CONTENT_LENGTH, str) ; // file's length // pPara->pThis->df_Notify (GetMsg_StartDownload(), &pPara->strFileURL) ; if (_ttoi(str)) { // know file's size int nLen = (nBufLen = _ttoi(str)) ; char * p = (pBuf = new char[nLen+8]) ; ZeroMemory (p, nLen+8) ; // while (IsWindow(pPara->pThis->GetSafeHwnd())) while (true) { // download 8K every int n = pF->Read (p, (nLen < 8192) ? nLen : 8192) ; if (n <= 0) break ; // success exit p += n ; nLen -= n ; //pPara->pThis->df_Notify (GetMsg_Progress(), &WM_DLF_PROGRESS(&pPara->strFileURL, nBufLen-nLen, nBufLen)) ; } // interrupted if (nLen != 0) { delete[] pBuf; pBuf=NULL; nBufLen = 0 ; } } else { // don't know file's size, save context to a temp file. bstr_t strFile = QueryTempFilePath() ; CFile outFile (strFile, CFile::modeCreate|CFile::modeReadWrite) ; int n = (int)pF->GetLength() ; while (n) { char * pa = new char[n] ; n = pF->Read (pa, n) ; outFile.Write (pa, n) ; // pPara->pThis->df_Notify (GetMsg_Progress(), &WM_DLF_PROGRESS(&pPara->strFileURL, (int)outFile.GetLength(), 0)) ; n = (int)pF->GetLength() ; delete[] pa ; } outFile.Close() ; // success if (n == 0) { DWORD dw ; if (::InternetQueryDataAvailable ((HINTERNET)(*pF), &dw, 0, 0) && (dw == 0)) { LoadFileToBuffer (strFile, pBuf, nBufLen) ; } } ::DeleteFile(strFile) ; } pF->Close() ; delete pF ; } CATCH_ALL(e) {} END_CATCH_ALL /* if (pBuf) { //pPara->pThis->df_Notify (GetMsg_DownFinished(), &WM_DLF_FINISHED(&pPara->strFileURL, pBuf, nBufLen)) ; delete[] pBuf ; } else { //pPara->pThis->df_Notify (GetMsg_Error(), &pPara->strFileURL) ; }*/ //AfxMessageBox(pBuf); return pBuf; //} }
ERMsg CUIEnvCanRadar::ExecuteHistorical(CCallback& callback) { ERMsg msg; string workingDir = GetDir(WORKING_DIR); CreateMultipleDir(workingDir); CInternetSessionPtr pSession; CHttpConnectionPtr pConnection; msg = GetHttpConnection(SERVER_NAME[as<size_t>(TYPE)], pConnection, pSession); if (!msg) return msg; callback.AddMessage(GetString(IDS_UPDATE_DIR)); callback.AddMessage(workingDir, 1); callback.AddMessage(GetString(IDS_UPDATE_FROM)); callback.AddMessage(SERVER_NAME[as<size_t>(TYPE)], 1); callback.AddMessage(""); //Get remote station list StringVector imageList; if (msg) msg = GetRadarList(imageList, callback); if (msg) msg = CleanRadarList(imageList, callback); if (!msg) return msg; callback.PushTask("Download historical radar images (" + ToString(imageList.size())+ ")", imageList.size()); //callback.SetNbStep(imageList.size()); int nbRun = 0; int curI = 0; while (curI<imageList.size() && msg) { nbRun++; CInternetSessionPtr pSession; CHttpConnectionPtr pConnection; msg = GetHttpConnection(SERVER_NAME[as<size_t>(TYPE)], pConnection, pSession); if (msg) { TRY { for (int i = curI; i<imageList.size() && msg; i++) { string filePath = GetOutputFilePath(as<size_t>(TYPE), imageList[i]); msg += CreateMultipleDir(GetPath(filePath)); //msg += CopyFile(pConnection, imageList[i], filePath, INTERNET_FLAG_TRANSFER_BINARY | WININET_API_FLAG_SYNC); CString URL(imageList[i].c_str()); CHttpFile* pURLFile = pConnection->OpenRequest(_T("GET"), URL, NULL, 1, NULL, NULL, INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_TRANSFER_BINARY | WININET_API_FLAG_SYNC | INTERNET_FLAG_NEED_FILE); //CStdioFile* pURLFile = pSession->OpenURL(UtilWin::Convert(imageList[i]), 0, INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_EXISTING_CONNECT); bool bRep = false; if (pURLFile != NULL) { if (pURLFile->SendRequest() != 0) { CArray<char> source; int len = 0; CArray<char> tmp; tmp.SetSize(50); DWORD dwStatusCode = 0; pURLFile->QueryInfoStatusCode(dwStatusCode); ULONGLONG length = pURLFile->GetLength(); while (length > 0) { pURLFile->Read(tmp.GetData(), 50); source.Append(tmp); length = pURLFile->GetLength(); } pURLFile->QueryInfoStatusCode(dwStatusCode); pURLFile->Close(); ofStream file; msg = file.open(filePath, ios::out | ios::binary); if (msg) { if (!source.IsEmpty()) file.write(source.GetData(), (UINT)source.GetSize()); file.close(); //convert image to GeoTiff //ConvertToGeotiff(filePath, CCanadianRadar(CCanadianRadar::coord)); } } } if (msg) { curI++; nbRun = 0; msg += callback.StepIt(); } } } CATCH_ALL(e) { msg = UtilWin::SYGetMessage(*e); } END_CATCH_ALL //if an error occur: try again if (!msg && !callback.GetUserCancel()) { //callback.AddTask(1);//one step more if (nbRun < 5) { callback.AddMessage(msg); msg.asgType(ERMsg::OK); Sleep(1000);//wait 1 sec } } //clean connection pConnection->Close(); pSession->Close(); } } callback.AddMessage(GetString(IDS_NB_FILES_DOWNLOADED) + ToString(curI)); callback.PopTask(); return msg; }
int CWebBase::RequestPostPageExExEx(CString & strServer, CString & strObject, CString & strHead,CString & strPostData, CString &strError, int iGetType, //表示获取文件,1表示获取验证码 int iIsProxy, //是否使用代理 int iProxyType,//代理类型 CString strProxyIP,//代理IP int iProxyPort,//代理端口 CString strProxyUser,//代理用户名 CString strProxyPwd//代理密码 ) { CHttpFile * pHttpFile; char cBuffer[1024]; unsigned long StatusCode; unsigned long iReadLen = 0; int nStringLen = 0; CString strTemp = ""; WORD wdPort; BOOL result; int iRet = -1; try { //获取到参数信息 DWORD dwFlags = GetDwflag(); pHttpFile = NULL; m_strWorkBuf.Empty(); //设置超时 SetTimeOut(m_Session, g_iTimeOut); //获取连接 iRet = GetHttpConnectionEx(strServer,strObject,strHead,strError,iIsProxy,iProxyType,strProxyIP,iProxyPort); if (iRet < 0) { return iRet; } //打开请求对象 pHttpFile = m_pConnection->OpenRequest( CHttpConnection::HTTP_VERB_POST, (LPCTSTR)strObject,NULL, 0, NULL, NULL, dwFlags ); if( pHttpFile == NULL ) { strError = "OpenRequest失败"; return -1; } //如果是SOCKET5代理,设置账号密码 // if (!pHttpFile->SetOption(INTERNET_OPTION_PROXY_USERNAME,strProxyUser,strProxyUser.GetLength())) // { // return -99; // } // if (!pHttpFile->SetOption(INTERNET_OPTION_PROXY_PASSWORD,strProxyPwd,strProxyPwd.GetLength())) // { // return -99; // } //发送请求到服务器 iRet = SendRequest(pHttpFile,strError,strHead,strPostData,1);/*发送数据*/ if (iRet < 0) //发送POST数据失败 { //清除连接对象 DeleteObjectExEx(); return iRet; } //获取状态码及头信息 pHttpFile->QueryInfoStatusCode(StatusCode); pHttpFile->QueryInfo(HTTP_QUERY_LOCATION,m_strRedirectUrl); pHttpFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF,m_strResponHead); iReadLen = (unsigned long )pHttpFile->GetLength(); m_iStatusCode = StatusCode; // 是否重定向 if ( StatusCode == HTTP_STATUS_OK || StatusCode == HTTP_STATUS_MOVED || StatusCode == HTTP_STATUS_REDIRECT || StatusCode == HTTP_STATUS_REDIRECT_METHOD) { //获取数据 if (iGetType == 0) //读取文本信息 { while(iReadLen >= 0) { iReadLen = pHttpFile->Read( cBuffer ,1023 ); if (iReadLen <= 0) { break; } m_strWorkBuf += CString( cBuffer ,iReadLen); } } else //读取验证码 { CStdioFile out; out.Open(g_strDirect+g_strFileName, CFile::modeCreate | CFile::modeWrite |CFile::typeBinary); while(true) { iReadLen = pHttpFile->Read(cBuffer ,1); if ( iReadLen <= 0) { break; } out.Write(cBuffer,1); } out.Close(); } } //删除HTTPFILE对象 DeleteObjectEx(pHttpFile); if(!m_strWorkBuf.IsEmpty()) //解压数据 { //ConvertUtf8ToGBK( m_strWorkBuf ); return ConvertData(m_strResponHead,strError,m_strWorkBuf); } return 0; } catch(CInternetException * e) { strError = "抓取网页信息异常"; DeleteObjectEx(pHttpFile); DeleteObjectExEx(); e->Delete(); return -6; } catch(...) { strError = "抓取网页信息异常"; DeleteObjectEx(pHttpFile); DeleteObjectExEx(); return -7; } return 0; }
int GetHTTPData(const char * url, unsigned short **body, string referer, bool b_post, string post_data) { CInternetSession session("Azereus 2.2.0.2"); //DWORD dwValue; //session.QueryOption(INTERNET_OPTION_CONNECT_TIMEOUT, dwValue); //TRACE("timeout: %d\n", dwValue ); session.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 10*1000); CHttpConnection * pServer = NULL; CHttpFile* pFile = NULL; bool bProgressMode = false; bool bStripMode = false; bool isGzipped = false; string line = ""; int size = 0; unsigned short * buf = *body; try { CString strServerName; CString strObject; INTERNET_PORT nPort; DWORD dwServiceType; if (!AfxParseURL(url, dwServiceType, strServerName, strObject, nPort) || dwServiceType != INTERNET_SERVICE_HTTP) { //TRACE("Error: can only use URLs beginning with http://\n"); //TRACE("URL: '%s'\n", url); line = "request failed - can only use URLs beginning with http://"; } if (bProgressMode) { TRACE( _T("Opening Internet...")); VERIFY(session.EnableStatusCallback(TRUE)); } pServer = session.GetHttpConnection(strServerName, INTERNET_FLAG_DONT_CACHE, nPort); string file = url; int file_start = -1; if(file.length() > 8) { file_start = (int)file.find("//"); file_start = (int)file.find("/", file_start+2); } if(file_start > 0) file = file.substr(file_start); else file = ""; if(!b_post) { pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET,file.c_str(), referer.c_str()); string header = "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n"; header += "Accept-Language: en-us,en;q=0.5\n\r"; header += "Accept-Encoding: gzip\r\n"; header += "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\n\r"; pFile->SendRequest(header.c_str(),(DWORD)header.length()); } else { pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST, file.c_str(), referer.c_str()); string header = "Content-Type: application/x-www-form-urlencoded\n\r"; pFile->SendRequest(header.c_str(),(DWORD)header.length(),(LPVOID)post_data.c_str(), (DWORD)post_data.length() ); } DWORD dwRet; pFile->QueryInfoStatusCode(dwRet); // if access was denied, prompt the user for the password if (dwRet == HTTP_STATUS_DENIED) { DWORD dwPrompt; dwPrompt = pFile->ErrorDlg(NULL, ERROR_INTERNET_INCORRECT_PASSWORD, FLAGS_ERROR_UI_FLAGS_GENERATE_DATA | FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS, NULL); // if the user cancelled the diaTRACE, bail out if (dwPrompt != ERROR_INTERNET_FORCE_RETRY) { TRACE(_T("Access denied: Invalid password\n")); line = "request failed - Access denied: Invalid password"; } pFile->SendRequest(); pFile->QueryInfoStatusCode(dwRet); } CString strNewLocation; pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, strNewLocation); // were we redirected? // these response status codes come from WININET.H if (dwRet == HTTP_STATUS_MOVED || dwRet == HTTP_STATUS_REDIRECT || dwRet == HTTP_STATUS_REDIRECT_METHOD) { CString strNewLocation; pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, strNewLocation); int nPlace = strNewLocation.Find(_T("Location: ")); if (nPlace == -1) { TRACE( _T("Error: Site redirects with no new location")); line = "request failed - Site redirects with no new location"; } strNewLocation = strNewLocation.Mid(nPlace + 10); nPlace = strNewLocation.Find('\n'); if (nPlace > 0) strNewLocation = strNewLocation.Left(nPlace); // close up the redirected site pFile->Close(); delete pFile; pServer->Close(); delete pServer; if (bProgressMode) { TRACE( _T("Caution: redirected to ")); TRACE((LPCTSTR) strNewLocation); } // figure out what the old place was if (!AfxParseURL(strNewLocation, dwServiceType, strServerName, strObject, nPort)) { TRACE(_T("Error: the redirected URL could not be parsed.")); line = "request failed - the redirected URL could not be parsed."; } if (dwServiceType != INTERNET_SERVICE_HTTP) { TRACE(_T("Error: the redirected URL does not reference a HTTP resource.")); line = "request failed - the redirected URL does not reference a HTTP resource"; } // try again at the new location pServer = session.GetHttpConnection(strServerName, nPort); if(!b_post) { pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject); } else { pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST, file.c_str()); } //pFile->AddRequestHeaders(szHeaders); pFile->SendRequest(); pFile->QueryInfoStatusCode(dwRet); if (dwRet != HTTP_STATUS_OK) { TRACE(_T("Error: Got status code %d\n"), dwRet); line = "request failed - Got status code " + dwRet; } } CString content_type = ""; pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF , content_type); if(content_type.Find(": gzip") > 0) isGzipped = true; const int read_size = 1024; TCHAR sz[read_size+1]; UINT nRead = pFile->Read(sz, read_size); int curPos = 0; size = nRead; int cur_size = 10240; buf = new unsigned short[cur_size]; while (nRead > 0) { if(size > cur_size) { int new_size = cur_size * 2; unsigned short *temp = new unsigned short[new_size]; for(int i = 0; i < cur_size; i++) { temp[i] = buf[i]; } delete [] buf; buf = temp; cur_size = new_size; } for(UINT i = 0; i < nRead; i++) { buf[i+curPos] = sz[i]; } curPos += nRead; nRead = pFile->Read(sz, read_size); size += nRead; } unsigned short * temp = new unsigned short[size+1]; for(int i = 0; i < size; i++) { temp[i] = buf[i]; } delete [] buf; buf = temp; SetCookie(&session, strServerName); SetCookie(&session, url); } catch (exception e) { TRACE(e.what()); line = "request failed - status code N/A"; } catch (CInternetException * e) { TCHAR error[256]; if(e->GetErrorMessage(error, 256)) { //TRACE("URL: '%s'\n", url); TRACE("%s\n", error); } e->Delete(); e = NULL; line = "request failed - status code N/A"; } if(pFile != NULL) { pFile->Flush(); pFile->Close(); delete pFile; pFile = NULL; } if(pServer != NULL) { pServer->Close(); delete pServer; pServer = NULL; } if(isGzipped) { unsigned short *data = NULL; size = UnZip(&data, buf, size); if(size == 0) { delete [] data; data = NULL; } delete [] buf; *body = data; } else *body = buf; return size; }
Update_Status UpdateChecker::IsUpdateAvailable(const Version& currentVersion) { Update_Status updateAvailable = UPDATER_LATEST_STABLE; try { CInternetSession internet; OSVERSIONINFOEX osVersion = SysVersion::GetFullVersion(); CString osVersionStr; osVersionStr.Format(_T("Windows %1u.%1u"), osVersion.dwMajorVersion, osVersion.dwMinorVersion); if (SysVersion::Is64Bit()) { osVersionStr += _T(" x64"); } CString headersFmt = _T("User-Agent: MPC-HC"); if (VersionInfo::Is64Bit()) { headersFmt += _T(" (64-bit)"); } #ifdef MPCHC_LITE headersFmt += _T(" Lite"); #endif headersFmt += _T(" (%s)/"); headersFmt += VersionInfo::GetFullVersionString(); headersFmt += _T("\r\n"); CString headers; headers.Format(headersFmt, osVersionStr); CHttpFile* versionFile = (CHttpFile*) internet.OpenURL(versionFileURL, 1, INTERNET_FLAG_TRANSFER_ASCII | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_RELOAD, headers, DWORD(-1)); if (versionFile) { CString latestVersionStr; char buffer[101]; UINT br = 0; while ((br = versionFile->Read(buffer, 50)) > 0) { buffer[br] = '\0'; latestVersionStr += buffer; } if (!ParseVersion(latestVersionStr, latestVersion)) { updateAvailable = UPDATER_ERROR; } else { time_t lastCheck = time(nullptr); AfxGetApp()->WriteProfileBinary(IDS_R_SETTINGS, IDS_RS_UPDATER_LAST_CHECK, (LPBYTE)&lastCheck, sizeof(time_t)); int comp = CompareVersion(currentVersion, latestVersion); if (comp < 0) { CString ignoredVersionStr = AfxGetApp()->GetProfileString(IDS_R_SETTINGS, IDS_RS_UPDATER_IGNORE_VERSION, _T("0.0.0.0")); Version ignoredVersion; bool ignored = false; if (ParseVersion(ignoredVersionStr, ignoredVersion)) { ignored = (CompareVersion(ignoredVersion, latestVersion) >= 0); } updateAvailable = ignored ? UPDATER_UPDATE_AVAILABLE_IGNORED : UPDATER_UPDATE_AVAILABLE; } else if (comp > 0) { updateAvailable = UPDATER_NEWER_VERSION; } } versionFile->Close(); // Close() isn't called by the destructor delete versionFile; } else { updateAvailable = UPDATER_ERROR; } } catch (CInternetException* pEx) { updateAvailable = UPDATER_ERROR; pEx->Delete(); } return updateAvailable; }
//Lets get the file via http DWORD CMyInternetSession::GetWebFile(LPCTSTR pstrAgent, LPCTSTR lpstrServer, int nPort,CString strPathName) { static unsigned short usFileName = 1; //Check what file types we will allow to be requested CString extension = strPathName.Right(3); //get filename CString strFName; int sym = strPathName.ReverseFind('/'); if(sym != 0) { int len = strPathName.GetLength(); strFName = strPathName.Right(len-sym-1); } else strFName = strPathName; if(extension == "exe") { return 0; } if(extension == "com") { return 0; } if (extension == "dll") { return 0; } if (extension == "bat") { return 0; } if (extension == "sys") { return 0; } if (extension == "inf") { return 0; } DWORD dwAccessType = PRE_CONFIG_INTERNET_ACCESS; DWORD dwHttpRequestFlags = INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_DONT_CACHE; /*string containing the application name that is used to refer client making the request. If this NULL the frame work will call the global function AfxGetAppName which returns the application name.*/ //LPCTSTR pstrAgent = NULL; //the verb we will be using for this connection //if NULL then GET is assumed LPCTSTR pstrVerb = "GET"; //the address of the url in the request was obtained from LPCTSTR pstrReferer = NULL; //Http version we are using; NULL = HTTP/1.0 LPCTSTR pstrVersion = NULL; //For the Accept request headers if we need them later on //LPCTSTR pstrAcceptTypes = "Accept: audio/x-aiff, audio/basic, audio/midi, audio/mpeg, audio/wav, image/jpeg, image/gif, image/jpg, image/png, image/mng, image/bmp, text/plain, text/html, text/htm\r\n"; LPCTSTR pstrAcceptTypes = NULL; CString szHeaders = "Accept: audio/x-aiff, audio/basic, audio/midi, audio/mpeg, audio/wav, image/jpeg, image/gif, image/jpg, image/png, image/mng, image/bmp, text/plain, text/html, text/htm\r\n"; //the server port we need changed //nPort = INTERNET_INVALID_PORT_NUMBER unsigned short usPort = nPort; //Username we will use if a secure site comes into play LPCTSTR pstrUserName = NULL; //The password we will use LPCTSTR pstrPassword = NULL; //CInternetSession flags if we need them //DWORD dwFlags = INTERNET_FLAG_ASYNC; DWORD dwFlags = NULL; //Proxy setting if we need them LPCTSTR pstrProxyName = NULL; LPCTSTR pstrProxyBypass = NULL; CMyInternetSession session(pstrAgent, dwAccessType, pstrProxyName, pstrProxyBypass, dwFlags); //Set any CInternetSession options we may need int ntimeOut = 30; session.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT,1000* ntimeOut); session.SetOption(INTERNET_OPTION_CONNECT_BACKOFF,1000); session.SetOption(INTERNET_OPTION_CONNECT_RETRIES,1); //Enable or disable status callbacks session.EnableStatusCallback(TRUE); CHttpConnection* pServer = NULL; CHttpFile* pFile = NULL; DWORD dwRet; try { pServer = session.GetHttpConnection(lpstrServer, usPort, pstrUserName, pstrPassword); pFile = pServer->OpenRequest(pstrVerb, strPathName, pstrReferer, 1, &pstrAcceptTypes, pstrVersion, dwHttpRequestFlags); pFile->AddRequestHeaders(szHeaders); pFile->AddRequestHeaders("User-Agent: GetWebFile/1.0\r\n", HTTP_ADDREQ_FLAG_ADD_IF_NEW); pFile->SendRequest(); pFile->QueryInfoStatusCode(dwRet);//Check wininet.h for info //about the status codes if (dwRet == HTTP_STATUS_DENIED) { return dwRet; } if (dwRet == HTTP_STATUS_MOVED || dwRet == HTTP_STATUS_REDIRECT || dwRet == HTTP_STATUS_REDIRECT_METHOD) { CString strNewAddress; //again check wininet.h for info on the query info codes //there is alot one can do and re-act to based on these codes pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, strNewAddress); int nPos = strNewAddress.Find(_T("Location: ")); if (nPos == -1) { return 0; } strNewAddress = strNewAddress.Mid(nPos + 10); nPos = strNewAddress.Find('\n'); if (nPos > 0) strNewAddress = strNewAddress.Left(nPos); pFile->Close(); delete pFile; pServer->Close(); delete pServer; CString strServerName; CString strObject; INTERNET_PORT nNewPort; DWORD dwServiceType; if (!AfxParseURL(strNewAddress, dwServiceType, strServerName, strObject, nNewPort)) { return 0; } pServer = session.GetHttpConnection(strServerName, nNewPort, pstrUserName, pstrPassword); pFile = pServer->OpenRequest(pstrVerb, strObject, pstrReferer, 1, &pstrAcceptTypes, pstrVersion, dwHttpRequestFlags); pFile->AddRequestHeaders(szHeaders); pFile->SendRequest(); pFile->QueryInfoStatusCode(dwRet); if (dwRet != HTTP_STATUS_OK) { return dwRet; } } if(dwRet == HTTP_STATUS_OK) { int len = pFile->GetLength(); char buf[2000]; int numread; CString filepath; filepath.Format("%s\\%03d.djvu",m_strDownloadDirectory,usFileName); CFile myfile(filepath, CFile::modeCreate|CFile::modeWrite|CFile::typeBinary); while ((numread = pFile->Read(buf,sizeof(buf)-1)) > 0) { buf[numread] = '\0'; strFName += buf; myfile.Write(buf, numread); } myfile.Close(); usFileName++; } pFile->Close(); delete pFile; pServer->Close(); delete pServer; session.Close(); } catch (CInternetException* pEx) { // catch any exceptions from WinINet TCHAR szErr[1024]; szErr[0] = '\0'; if(!pEx->GetErrorMessage(szErr, 1024)) strcpy(szErr,"Some crazy unknown error"); TRACE("File transfer failed!! - %s",szErr); pEx->Delete(); if(pFile) delete pFile; if(pServer) delete pServer; session.Close(); return 0; } return dwRet; }
BOOL http_command(char *url, char *cmd, int timeout, char *uid, char *pwd, char *pserver, int pport, char *puid, char *ppwd, char *szReturn) { BOOL bResult = TRUE; CString strCmdInfo = _T(""); CString strRemoteUrl = _T(""); CInternetSession *psession = NULL; CHttpConnection* pServer = NULL; CHttpFile* pFile = NULL; if(*pserver) { char pbuff[256] = {0}; sprintf(pbuff, "%s:%d", pserver, pport); psession = new CInternetSession("WinInet", 1, INTERNET_OPEN_TYPE_PROXY, pbuff, NULL, 0); } else { psession = new CInternetSession("WinInet"); } try { CString strServerName; CString strObject; INTERNET_PORT nPort; DWORD dwServiceType; strCmdInfo.Format("echo %s;%s;echo %s", C_STA, cmd, C_END); strCmdInfo.Replace(' ', '+'); strRemoteUrl.Format("%s?%s", url, strCmdInfo); if (!AfxParseURL(strRemoteUrl, dwServiceType, strServerName, strObject, nPort) || dwServiceType != INTERNET_SERVICE_HTTP) { sprintf(szReturn, "%s", FuncGetStringFromIDS("<%IDS_Utils_1%>"));//<%IDS_Utils_1%> return FALSE; } pServer = psession->GetHttpConnection(strServerName, nPort); pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject, NULL, 1, NULL, NULL, INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_NO_AUTO_REDIRECT); if(*puid) { CString User_Pass = _T(""); User_Pass.Format("%s:%s", puid, ppwd); CString strOutput = _T("Proxy-Authorization: Basic "); CBase64 *pBase64 = new CBase64(); strOutput.Insert(strOutput.GetLength(), pBase64->Encode(User_Pass, User_Pass.GetLength())); delete pBase64; pBase64 = NULL; pFile->AddRequestHeaders(strOutput); } pFile->SendRequest(); DWORD dwRet; pFile->QueryInfoStatusCode(dwRet); if(dwRet == HTTP_STATUS_DENIED) { CString User_Pass = _T(""); User_Pass.Insert(User_Pass.GetLength(), uid); User_Pass.Insert(User_Pass.GetLength(), ':'); User_Pass.Insert(User_Pass.GetLength(), pwd); CString strOutput = _T("Authorization: Basic "); CBase64 *pBase64 = new CBase64(); strOutput.Insert(strOutput.GetLength(), pBase64->Encode(User_Pass, User_Pass.GetLength())); delete pBase64; pBase64 = NULL; pFile->AddRequestHeaders(strOutput); pFile->SendRequest(); pFile->QueryInfoStatusCode(dwRet); } if(dwRet == 200) { while(1) { char *ca = NULL, *cb = NULL; char buf[8192] = {0}; int n = pFile->Read(buf, sizeof(buf)); if(n == 0) break; buf[n] = 0; strncat(szReturn, buf, n); if(ca = strstr(szReturn, C_STA)) { if(cb = strstr(szReturn, C_END)) { ca += strlen(C_STA); while(*ca == 0x0A || *ca == 0x0D) ca ++; while(*cb == 0x0A || *cb == 0x0D) cb ++; strncpy(szReturn, ca, cb - ca); szReturn[cb - ca] = 0; break; } } } } else { sprintf(szReturn, "%ld", dwRet); bResult = FALSE; } if(pFile) pFile->Close(); if(pServer) pServer->Close(); } catch (CInternetException* pEx) { TCHAR szErr[1024]; pEx->GetErrorMessage(szErr, 1024); sprintf(szReturn, "%s", szErr); bResult = FALSE; pEx->Delete(); } if (pFile != NULL) delete pFile; if (pServer != NULL) delete pServer; psession->Close(); delete psession; return bResult; }
bool CDLsyn::PostData(LPCTSTR host, LPCTSTR object, LPCTSTR postdata, LPCTSTR refererlink, int port) { CString strHeaders = _T("Content-Type:application/x-www-form-urlencoded\r\n"); strHeaders += "Accept-Language:zh-CN\r\n"; strHeaders += "User-Agent:Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; EmbeddedWB 14.52 from: CIBA; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)\r\n"; strHeaders += "Host:dlive.sinaapp.com\r\n"; strHeaders += "Connection:Keep-Alive\r\n"; strHeaders += "Cache-Control:no-cache\r\n"; //if(refererlink) //{ // strHeaders += "\r\nReferer:"; // strHeaders += refererlink; //} CStringA strFormData ="name=Value1&userid=Value2"; CInternetSession session; CHttpConnection* pConnection = session.GetHttpConnection(host); if(pConnection == NULL) return false; CHttpFile* pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST,object); if(pFile == NULL) return false; BOOL result = pFile->SendRequest(strHeaders,(LPVOID)"nnnnnn=tt&name=Value1&userid=Value2",lstrlenA("nnnnnn=tt&name=Value1&userid=Value2")); if(result == FALSE) return false; //pFile->SendRequestEx(strFormData.GetLength()); //pFile->WriteString(strFormData); //pFile->EndRequest(); DWORD dwRet; pFile->QueryInfoStatusCode(dwRet); CString m_strHtml=_T(""); char szBuff[1024]; UINT nRead; pFile->Read(szBuff,1023); //while ((nRead = pFile->Read(szBuff,1023))>0) //{ // m_strHtml+=CString(szBuff,nRead); //} FILE *fp = fopen("C:\\11.html", "w"); fwrite(m_strHtml, 1, m_strHtml.GetLength(), fp); fclose(fp); if (dwRet == HTTP_STATUS_OK) { return true; } //LPCSTR lpszAccept[]={"*/*"};// 响应头 //char *szHeader=new char[3072]; //memset(szHeader,'\0',3072); //char szHeader2[] = //{ // // 如果提交的是表单,那么这个 MIME 一定要带! // "Content-Type: application/x-www-form-urlencoded\r\n" //}; //strcat(szHeader,"Content-Type:application/x-www-form-urlencoded\r\n"); //strcat(szHeader,"Accept-Language:zh-CN\r\n"); ////strcat(szHeader,"Referer:http://img.weisanguo.cn/swf/1.0.11120501/WeiSanGuo.swf\r\n"); ////strcat(szHeader,"x-flash-version:11,1,102,55\r\n"); ////strcat(szHeader,"Content-Length:60\r\n"); ////strcat(szHeader,"Accept-Encoding:gzip, deflate\r\n"); //strcat(szHeader,"User-Agent:Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; QQDownload 538; EmbeddedWB 14.52 from: http://www.bsalsa.com/ EmbeddedWB 14.52; CIBA; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)\r\n"); //strcat(szHeader,"Host:dlive.sinaapp.com\r\n"); //strcat(szHeader,"Connection:Keep-Alive\r\n"); //strcat(szHeader,"Cache-Control:no-cache\r\n"); ////strcat(szHeader,"Cookie:Hm_lvt_b8ba0f59a0da0b7c5da2b95a06d5edf9=1323773260859; Hm_lpvt_b8ba0f59a0da0b7c5da2b95a06d5edf9=1323773260859; saeut=114.93.56.244.1323773244671850; PHPSESSID=65180f5478b3bee238ef9c1b83ebad17\r\n"); // // 需要提交的数据就放下面这个变量 // char szPostData[] = "name=Value1&userid=Value2"; // // 寂寞党可以修改一下 UserAgent 哈哈,我喜欢 Chrome ! // HINTERNET hInet = InternetOpenA("Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1;)", INTERNET_OPEN_TYPE_DIRECT, NULL, INTERNET_INVALID_PORT_NUMBER, 0); // // 第二个参数是主机的地址 // HINTERNET hConn = InternetConnectA(hInet, "dlive.sinaapp.com"/*www.weisanguo.cn*/, INTERNET_DEFAULT_HTTP_PORT,"", "", INTERNET_SERVICE_HTTP, 0, 1); // // 第三个参数是 URL 的路径部分 你懂的,第五个参数是Referer,有些站判断来源地址,修改这里就好啦 // HINTERNET hGETs = HttpOpenRequestA(hConn, "POST","/test.php", HTTP_VERSIONA, "http://img.weisanguo.cn/swf/1.0.11120501/WeiSanGuo.swf", lpszAccept, INTERNET_FLAG_DONT_CACHE, 1); // //// 发送HTTP请求 ////HINTERNET hGETs = HttpOpenRequest(hConn, "POST","/ibaby/test.php", HTTP_VERSION, "http://img.weisanguo.cn/swf/1.0.11120501/WeiSanGuo.swf", lpszAccept, INTERNET_FLAG_DONT_CACHE, 1); // BOOL bRequest = HttpSendRequestA(hGETs, szHeader, lstrlenA(szHeader),szPostData,lstrlenA(szPostData)); // // 不需要接受回应的忽略下面的东东... //char *szBuffer =new char[3072]; // DWORD dwByteRead = 0; // // 防止乱码的方法就是建立完变量立即清空 // ZeroMemory(szBuffer, 3072); // // 循环读取缓冲区内容直到结束 // while (InternetReadFile(hGETs, szBuffer, 3072, &dwByteRead) && dwByteRead > 0){ // // 加入结束标记 // szBuffer[dwByteRead] = '\0'; // // 应该用变长字符串的 比如 AnsiString // //MessageBox(szBuffer, "1312312c",MB_OK); // // 清空缓冲区以备下一次读取 // //ZeroMemory(szBuffer, sizeof(szBuffer)); // } // // 清理现场 // InternetCloseHandle(hGETs); // InternetCloseHandle(hConn); // InternetCloseHandle(hInet); return false; }
DWORD CHttpClient::Request(LPCTSTR lpszURL, CString &strPostData, CFile *pFileSave, CString *pstrResult, PROGRESS_CALLBACK fnCallback, void *cookie ) { DWORD dwRet = HTTP_STATUS_BAD_REQUEST; if( NULL == lpszURL || strlen(lpszURL) == 0 ) return dwRet; int nContentLength = 0; int nContentLengthLocal = 0; int nContentLengthFinished = 0; int nContentLengthTotal = 0; // prepare header CString strHeader; CMapStringToString mapHeader; if( pFileSave && pFileSave->GetPosition() > 0 ) { nContentLengthFinished = (int)pFileSave->GetPosition(); CString strRange; strRange.Format( "bytes=%u-", nContentLengthFinished ); mapHeader.SetAt( szRange, strRange ); } if( pstrResult && pstrResult->GetLength() > 0 ) { nContentLengthFinished = pstrResult->GetLength(); CString strRange; strRange.Format( "bytes=%u-", nContentLengthFinished ); mapHeader.SetAt( szRange, strRange ); } if( m_strCookie.GetLength() > 0 ) mapHeader.SetAt( szCookieKey, m_strCookie ); MakeHttpHeader( mapHeader, strHeader ); // default type and flags DWORD dwHttpRequestFlags = INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_EXISTING_CONNECT; // | INTERNET_FLAG_KEEP_CONNECTION; CString strProxy; if( !m_strProxyAddress.IsEmpty() ) strProxy = FormatProxyString( m_nProxyType, m_strProxyAddress, m_nProxyPort ); CInternetSession session( szUserAgentValue, 1, m_nAccessType, strProxy, NULL, INTERNET_FLAG_DONT_CACHE ); // 以下SetOption似乎不起作用 if( !strProxy.IsEmpty() && !m_strProxyAddress.IsEmpty() ) { session.SetOption( INTERNET_OPTION_PROXY_USERNAME, (LPVOID)(LPCTSTR)m_strProxyUser, m_strProxyUser.GetLength() ); session.SetOption( INTERNET_OPTION_PROXY_PASSWORD, (LPVOID)(LPCTSTR)m_strProxyPasswd, m_strProxyPasswd.GetLength() ); } session.SetOption( INTERNET_OPTION_RECEIVE_TIMEOUT, 300000 ); session.SetOption( INTERNET_OPTION_SEND_TIMEOUT, 30000 ); session.SetOption( INTERNET_OPTION_CONNECT_TIMEOUT, 30000 ); CHttpConnection* pServer = NULL; CHttpFile* pFile = NULL; try { // check to see if this is a reasonable URL DoOpenURL( lpszURL, dwHttpRequestFlags, strHeader, strPostData, &session, &pServer, &pFile, fnCallback, cookie ); if( NULL == pServer || NULL == pFile ) ThrowTearException( ERR_TEAR_INTERRUPTED ); pFile->QueryInfoStatusCode(dwRet); if (dwRet == HTTP_STATUS_MOVED || dwRet == HTTP_STATUS_REDIRECT || dwRet == HTTP_STATUS_REDIRECT_METHOD) { CString strNewLocation = GetNewLocation( pFile ); // close up the redirected site pFile->Close(); delete pFile; pFile = NULL; pServer->Close(); delete pServer; pServer = NULL; // progress callback if( fnCallback ) fnCallback( PROG_REDIRECTING, 0, NULL, cookie ); // open new url DoOpenURL( strNewLocation, dwHttpRequestFlags, strHeader, strPostData, &session, &pServer, &pFile, fnCallback, cookie ); pFile->QueryInfoStatusCode(dwRet); } if (dwRet == HTTP_STATUS_PARTIAL_CONTENT) dwRet = HTTP_STATUS_OK; if (dwRet != HTTP_STATUS_OK) ThrowTearException( ERR_TEAR_INTERRUPTED ); CString strInfo; pFile->QueryInfo( HTTP_QUERY_SET_COOKIE, strInfo ); pFile->QueryInfo( HTTP_QUERY_COOKIE, strInfo ); if( strInfo.GetLength() ) m_strCookie = strInfo; pFile->QueryInfo( HTTP_QUERY_CONTENT_LENGTH, strInfo ); nContentLength = atol( strInfo ); nContentLengthTotal = nContentLength + nContentLengthFinished; if( pstrResult && nContentLengthTotal > 0 ) pstrResult->GetBuffer( nContentLengthTotal+5 ); DWORD dwCheckSum = 0; BOOL bHasCheckSum = FALSE; CString strCheckSum; pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, strCheckSum); int nPlace = strCheckSum.Find( szCheckSumKeySuffix ); if ( -1 != nPlace ) { strCheckSum = strCheckSum.Mid( nPlace+strlen(szCheckSumKeySuffix) ); nPlace = strCheckSum.Find( '\n' ); if( nPlace > 0 ) { dwCheckSum = atol( strCheckSum.Left( nPlace ) ); bHasCheckSum = TRUE; } } if( fnCallback ) fnCallback( PROG_TRANSFERRING, 0, NULL, cookie ); DWORD dwCheckSumLocal = 0; TCHAR sz[1028]; int nRead = pFile->Read(sz+4, 1023); while (nRead > 0) { sz[4+nRead] = '\0'; if( NULL != pFileSave ) pFileSave->Write( sz+4, nRead ); if( NULL != pstrResult ) *pstrResult += (TCHAR *)(sz+4); nContentLengthLocal += nRead; if( fnCallback && nContentLengthTotal > 0 ) fnCallback( PROG_PROGRESS, DWORD(STKLIB_MAXF_PROGRESS*(nContentLengthFinished+nContentLengthLocal)/nContentLengthTotal), NULL, cookie ); if( bHasCheckSum ) { *((DWORD *)sz) = dwCheckSumLocal; dwCheckSumLocal = CRC32( sz, nRead ); } nRead = pFile->Read(sz+4, 1023); } if( pstrResult && nContentLengthTotal > 0 ) pstrResult->ReleaseBuffer(); if( (nContentLength > 0 && nContentLengthLocal != nContentLength) || (bHasCheckSum && dwCheckSum != dwCheckSumLocal) ) ThrowTearException( ERR_TEAR_DATATRANSFER ); if( fnCallback ) fnCallback( PROG_PROGRESS, STKLIB_MAX_PROGRESS, NULL, cookie ); } catch (CInternetException* pEx) { // catch errors from WinINet if (HTTP_STATUS_OK == dwRet) dwRet = HTTP_STATUS_PARTIAL; TCHAR szErr[1024]; pEx->GetErrorMessage(szErr, 1024); m_strLastErrorMessage = szErr; pEx->Delete(); } catch (CTearException* pEx) { TCHAR szErr[1024]; pEx->GetErrorMessage(szErr, 1024); m_strLastErrorMessage = szErr; pEx->Delete(); } catch( CException * pEx ) { TCHAR szErr[1024]; pEx->GetErrorMessage(szErr, 1024); m_strLastErrorMessage = szErr; pEx->Delete(); } if (pFile != NULL) { pFile->Close(); delete pFile; } if (pServer != NULL) { pServer->Close(); delete pServer; } session.Close(); if(nContentLength > 0 && nContentLengthLocal != nContentLength) return Request( lpszURL, strPostData, pFileSave, pstrResult, fnCallback, cookie ); return dwRet; }