// 初始化更新列表 BOOL CUpdaterApp::_InitFileList() { BOOL bReturn(FALSE); CString strFileList(m_szServer); strFileList += _T("/Filelist.txt"); CInternetSession sess; sess.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 5000); sess.SetOption(INTERNET_OPTION_SEND_TIMEOUT, 1000); sess.SetOption(INTERNET_OPTION_RECEIVE_TIMEOUT, 5000); sess.SetOption(INTERNET_OPTION_DATA_SEND_TIMEOUT, 1000); sess.SetOption(INTERNET_OPTION_DATA_RECEIVE_TIMEOUT, 5000); sess.SetOption(INTERNET_OPTION_CONNECT_RETRIES, 1); try { CHttpFile* pHttpFile = (CHttpFile*)sess.OpenURL(strFileList, 1, INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_TRANSFER_ASCII, NULL, 0); if (pHttpFile) { DWORD dwErrCode(0); pHttpFile->QueryInfo(HTTP_QUERY_STATUS_CODE, dwErrCode); if (dwErrCode >= 200 && dwErrCode < 300) { CStringA strLineA; while (pHttpFile->ReadString((LPTSTR)strLineA.GetBuffer(512), 511)) { strLineA.ReleaseBuffer(); // MFC-bug CString strLine(strLineA); strLine.TrimLeft(); if (strLine.GetLength() > 0 && strLine[0] != _T('\\')) { continue; } std::vector<CString> vecStrs = Split(strLine, _T("^^^^^^")); if (vecStrs.size() >= 2) { LPUPDATEITEM pUpdateItem = new UPDATEITEM; ZeroMemory(pUpdateItem, sizeof(*pUpdateItem)); lstrcpyn(pUpdateItem->szFileName, vecStrs[0], MAX_PATH); lstrcpyn(pUpdateItem->szServerMD5, vecStrs[1], 33); m_arrUpdate.Add(pUpdateItem); } } pHttpFile->Close(); sess.Close(); bReturn = TRUE; } else { LOG(_T("网站访问错误码:%d"), dwErrCode); } } } catch (...) { LOG(_T("下载列表异常!")); } return bReturn; }
HRESULT CMainFrame::GetWMEVersionHttp(CString& WMEVersion) { HRESULT RetCode = S_OK; WMEVersion = "0.0.0"; CString Magic = GetRegString(HKEY_CURRENT_USER, DCGF_TOOLS_REG_PATH, "BBID"); CInternetSession Session; CHttpConnection* Server = NULL; CHttpFile* File = NULL; DWORD HttpRequestFlags = INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_NO_AUTO_REDIRECT; const TCHAR Headers[] = _T("Accept: text/*\r\nUser-Agent: WME ProjectMan\r\n"); CString Url = LOC("/str1086/http://www.dead-code.org/vercheck.php"); CString CurrVer; CurrVer.Format("%d.%d.%03d", DCGF_VER_MAJOR, DCGF_VER_MINOR, DCGF_VER_BUILD); Url += "?product=wme&ver=" + CurrVer; Url += "&bbid=" + Magic; if(DCGF_VER_BETA) Url += "&beta=1"; bool DotNet = RegKeyExists(HKEY_LOCAL_MACHINE, "Software\\Microsoft\\.NETFramework\\policy\\v2.0"); Url += "&dotnet=" + CString(DotNet?"1":"0"); CString ServerName; CString Object; INTERNET_PORT Port; DWORD ServiceType; try{ if(!AfxParseURL(Url, ServiceType, ServerName, Object, Port) || ServiceType != INTERNET_SERVICE_HTTP){ return E_FAIL; } Server = Session.GetHttpConnection(ServerName, Port); File = Server->OpenRequest(CHttpConnection::HTTP_VERB_GET, Object, NULL, 1, NULL, NULL, HttpRequestFlags); File->AddRequestHeaders(Headers); if(File->SendRequest()){ TCHAR sz[1024]; if(File->ReadString(sz, 1023)){ WMEVersion = Entry(1, CString(sz), '\n'); } } File->Close(); Server->Close(); } catch (CInternetException* pEx) { // catch errors from WinINet //TCHAR szErr[1024]; //pEx->GetErrorMessage(szErr, 1024); //MessageBox(szErr, LOC("/str1002/Error"), MB_OK|MB_ICONERROR); RetCode = E_FAIL; pEx->Delete(); } if (File != NULL) delete File; if (Server != NULL) delete Server; Session.Close(); return RetCode; }
void SoftUpdate::OnBnClickedButton1() { m_link.ShowWindow(SW_HIDE); m_gif.ShowWindow(SW_SHOW); m_gif.Load(_T("res\\checknew.gif")); m_gif.Draw(); checknew.EnableWindow(FALSE); DWORD dw; if(!IsNetworkAlive(&dw)) { m_gif.ShowWindow(SW_HIDE); m_link.ShowWindow(SW_SHOW); m_link.SetWindowText(_T("<a href=\"http://www.ltplayer.com/faq.html\">网络连接断开,请检查网络设置</a>")); checknew.EnableWindow(TRUE); return; } CInternetSession mysession; CHttpConnection *myconn=0; CHttpFile *myfile=0; mysession.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 5); //重试之间的等待延时 mysession.SetOption(INTERNET_OPTION_CONNECT_RETRIES, 1); //重试次数 try { myconn=mysession.GetHttpConnection(L"127.0.0.1"); myfile=myconn->OpenRequest(L"GET",L"/index.asp"); if(myfile->SendRequest()==0) { m_gif.ShowWindow(SW_HIDE); m_link.ShowWindow(SW_SHOW); m_link.SetWindowText(_T("<a href=\"http://www.ltplayer.com/faq.html\">网络连接断开,请检查网络设置</a>")); myfile->Close(); myconn->Close(); mysession.Close(); delete myfile; delete myconn; myfile=0; myconn=0; checknew.EnableWindow(TRUE); return; } } catch (CMemoryException* e) { myfile->Close(); myconn->Close(); mysession.Close(); delete myfile; delete myconn; myfile=0; myconn=0; return; } CString mystr; char tmp[1024]; while(myfile->ReadString((wchar_t*)tmp,1024)) { mystr+=tmp; } myfile->Close(); myconn->Close(); mysession.Close(); delete myfile; delete myconn; myfile=0; myconn=0; mystr=_T("{ptm:2012-7-16,ver:0.0.1.6}"); CString OFVERSION =GetJsonValue(mystr,_T("ver")); CString OFPUBLISH =GetJsonValue(mystr,_T("ptm")); if(OFVERSION=="" || OFPUBLISH=="") { m_gif.ShowWindow(SW_HIDE); m_link.ShowWindow(SW_SHOW); m_link.SetWindowText(_T("<a href=\"http://www.ltplayer.com/faq.html\">网络连接断开,请检查网络设置</a>")); checknew.EnableWindow(TRUE); return; } USES_CONVERSION; //CString mystr=_T("0.0.1.7"); CString newversion=OFVERSION; int index=0; OFVERSION.Remove(_T('.')); int versiontotal=atoi(W2A(OFVERSION)); if(versiontotal>USERVERSION) { CString cs; cs.Format(_T("<a href=\"http://www.ltplayer.com/download.html\">发现最新版本%s(%s),请点击更新</a>"),newversion,OFPUBLISH); m_gif.ShowWindow(SW_HIDE); m_link.ShowWindow(SW_SHOW); m_link.SetWindowText(cs); checknew.EnableWindow(TRUE); } else { m_gif.ShowWindow(SW_HIDE); m_link.ShowWindow(SW_SHOW); m_link.SetWindowText(_T("您使用的是最新版本,无需升级")); checknew.EnableWindow(TRUE); } }
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; }
//负责接收上传操作的页面的URL ,待上传的本地文件路径 int CWebBase::UploadFile(LPCTSTR strURL, LPCTSTR strLocalFileName) { ASSERT(strURL != NULL && strLocalFileName != NULL); BOOL bResult = FALSE; DWORD dwType = 0; CString strServer; CString strObject; INTERNET_PORT wPort = 0; DWORD dwFileLength = 0; char * pFileBuff = NULL; CHttpConnection * pHC = NULL; CHttpFile * pHF = NULL; CInternetSession cis; bResult = AfxParseURL(strURL, dwType, strServer, strObject, wPort); if(!bResult) { return FALSE; } CFile file; try { if(!file.Open(strLocalFileName, CFile::shareDenyNone | CFile::modeRead)) return FALSE; dwFileLength = file.GetLength(); if(dwFileLength <= 0) return FALSE; pFileBuff = new char[dwFileLength]; memset(pFileBuff, 0, sizeof(char) * dwFileLength); file.Read(pFileBuff, dwFileLength); const int nTimeOut = 5000; cis.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, nTimeOut); //联接超时设置 cis.SetOption(INTERNET_OPTION_CONNECT_RETRIES, 1); //重试1次 pHC = cis.GetHttpConnection(strServer, wPort); //取得一个Http联接 pHF = pHC->OpenRequest(CHttpConnection::HTTP_VERB_POST, strObject); if(!pHF->SendRequest(NULL, 0, pFileBuff, dwFileLength)) { delete[]pFileBuff; pFileBuff = NULL; pHF->Close(); pHC->Close(); cis.Close(); return FALSE; } DWORD dwStateCode = 0; pHF->QueryInfoStatusCode(dwStateCode); if(dwStateCode == HTTP_STATUS_OK) bResult = TRUE; } catch(CInternetException * pEx) { char sz[256] = ""; pEx->GetErrorMessage(sz, 25); CString str; str.Format("InternetException occur!\r\n%s", sz); AfxMessageBox(str); } catch(...) { DWORD dwError = GetLastError(); CString str; str.Format("Unknow Exception occur!\r\n%d", dwError); AfxMessageBox(str); } delete[]pFileBuff; pFileBuff = NULL; file.Close(); pHF->Close(); pHC->Close(); cis.Close(); return bResult; }
void CFtpDownloadThread::Run() { USES_CONVERSION; CInternetSession InternetSession; CFtpConnection * pFtpConn = NULL; CInternetFile * pFtpFile = NULL; CString strFtpUrl, fileDir; CFileException fileException; CFile file; UINT nFtpReadSize = 0; BYTE buffer[1024] = {0}; BOOL bIsOpenFile = FALSE; CFtpFileFind * pFtpFind = NULL; strFtpUrl.Format(_T("%s"), A2W(m_strFptURL.c_str())); try { pFtpConn = InternetSession.GetFtpConnection(strFtpUrl, m_strUsr.c_str()?NULL:m_strUsr.c_str(), m_strPwd.c_str()?NULL:m_strPwd.c_str(), m_nftpPort); } catch (CInternetException * pEx) { TCHAR sz[1024]; pEx->GetErrorMessage(sz, 1024); AfxMessageBox(sz); pEx->Delete(); m_nErrorCode = FTP_SERVER_CONNECT_FAILED; goto end; } if (pFtpConn == NULL) { m_nErrorCode = FTP_SERVER_CONNECT_FAILED; goto end; } fileDir.Format(_T("%s\\%s"), m_strSaveDir.c_str(), m_strFileName.c_str()); UINT nMode = 0; //CInternetFile不支持FTP协议的端点续传,需要自己实现。 /*if (PathFileExists(fileDir)) nMode = CFile::modeWrite; else*/ nMode = CFile::modeCreate | CFile::modeReadWrite | CFile::typeBinary; if (!file.Open(fileDir, nMode, &fileException)){ m_nErrorCode = ERR_OPEN_LOACAL_SAVE_FILE; goto end; } bIsOpenFile = TRUE; file.SeekToEnd(); m_nDownloadLen = file.GetLength(); pFtpFind = new CFtpFileFind(pFtpConn); if (!pFtpFind->FindFile(m_strFileName.c_str())) { m_nErrorCode = FTP_SERVER_FILE_OPEN_ERR; pFtpFind->Close(); delete pFtpFind; goto end; } pFtpFind->FindNextFile(); m_nFtpFileLen = pFtpFind->GetLength(); pFtpFind->Close(); delete pFtpFind; pFtpFile = pFtpConn->OpenFile(m_strFileName.c_str()); if (pFtpFile == NULL) { m_nErrorCode = FTP_SERVER_FILE_OPEN_ERR; goto end; } /*//CInternetFile不支持FTP协议的断点续传,需要自己实现。 if (m_nFtpFileLen != 0) pFtpFile->Seek(m_nDownloadLen, CInternetFile::begin);*/ while(TRUE) { if (!m_bIsStart) break; if (m_nDownloadLen >= m_nFtpFileLen) break; try { nFtpReadSize = pFtpFile->Read(buffer, sizeof(buffer)); } catch (CInternetException * pEx) { TCHAR sz[1024]; pEx->GetErrorMessage(sz, 1024); AfxMessageBox(sz); pEx->Delete(); m_nErrorCode = FTP_SERVER_CONNECT_FAILED; goto end; } if (nFtpReadSize <= 0) continue; try { file.Write(buffer, sizeof(buffer)); }catch(CFileException * pEx) { TCHAR sz[1024]; pEx->GetErrorMessage(sz, 1024); AfxMessageBox(sz); pEx->Delete(); m_nErrorCode = ERR_WRITE_LOCAL_FILE; goto end; } m_nDownloadLen += nFtpReadSize; } end: if (pFtpFile) { pFtpFile->Close(); delete pFtpFile; } if (pFtpConn) { pFtpConn->Close(); delete pFtpConn; } InternetSession.Close(); if (bIsOpenFile) file.Close(); m_bIsStart = FALSE; }
std::string CallHprose::DownloadHprose( std::string strHproseDownloadUrl, std::string strFileDir, std::string strFileName ) { CInternetSession sess; CHttpFile* pHttpFile; try { pHttpFile=(CHttpFile*)sess.OpenURL(strHproseDownloadUrl.c_str()); } catch(CException* e) { pHttpFile = 0; TCHAR msg[1024]; memset(msg, 0, 1024); e->GetErrorMessage(msg, 1023, NULL); ZTools::WriteZToolsFormatLog("打开URL失败:%s", msg); return ""; } DWORD dwStatus; DWORD dwBuffLen = sizeof(dwStatus); BOOL bSuccess = pHttpFile->QueryInfo(HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, &dwStatus, &dwBuffLen); int nReadBlockSize = 256*1024; char* pBuffer = new char[nReadBlockSize]; if( bSuccess && dwStatus>= 200&& dwStatus<300 ) { if (strFileName.length() == 0) { CString sContentDisposition; DWORD dwIndex = 0; bSuccess = pHttpFile->QueryInfo(HTTP_QUERY_CONTENT_DISPOSITION, sContentDisposition, &dwIndex); std::string strContentDisposition((LPCTSTR)sContentDisposition); std::string strKeyBegin("filename=\""); std::string strKeyEnd("\""); if (!strContentDisposition.empty()) { size_t nBegin = strContentDisposition.find(strKeyBegin) + strKeyBegin.length(); if (nBegin < strContentDisposition.length()) { size_t nEnd = strContentDisposition.find(strKeyEnd, nBegin); strFileName = strContentDisposition.substr(nBegin, nEnd - nBegin); } strFileName = deescapeURL(strFileName); ZTools::UTF8ToMB(strFileName); } } if (strFileName.length() == 0) { delete[] pBuffer; pBuffer = NULL; pHttpFile->Close(); //delete pHttpFile; sess.Close(); ZTools::WriteZToolsFormatLog("没有找到文件名"); return ""; } std::replace(strFileDir.begin(), strFileDir.end(), '/', '\\'); strFileDir.erase(strFileDir.find_last_not_of('\\') + 1); std::replace(strFileName.begin(), strFileName.end(), '/', '\\'); strFileName.erase(0, strFileName.find_first_not_of('\\')); std::string strFilePath = ZTools::FormatString("%s\\%s", strFileDir.c_str(), strFileName.c_str()); //先下载到临时文件中,下载成功后重命名 std::string strFilePathTemp = ZTools::FormatString("%s\\%s", strFileDir.c_str(), GuidToString(CreateGuid()).c_str()); if (!MakeSureDirectoryPathExists(strFilePath.c_str())) { delete[] pBuffer; pBuffer = NULL; pHttpFile->Close(); //delete pHttpFile; sess.Close(); ZTools::WriteZToolsFormatLog("创建文件夹失败:%s", strFilePath.c_str()); return ""; } CFile fileWrite; ULONGLONG dwFileLen = 0; DWORD dwWriteIndex = 0; dwFileLen = pHttpFile->SeekToEnd(); pHttpFile->SeekToBegin(); if(fileWrite.Open(strFilePathTemp.c_str(), CFile::modeWrite|CFile::modeCreate)) { int nCount = 0; while(dwWriteIndex < dwFileLen) { nCount = pHttpFile->Read(pBuffer, nReadBlockSize); fileWrite.Write(pBuffer, nCount); dwWriteIndex += nCount; } fileWrite.Close(); rename(strFilePathTemp.c_str(), strFilePath.c_str()); delete[] pBuffer; pBuffer = NULL; pHttpFile->Close(); delete pHttpFile; sess.Close(); if (PathFileExists(strFilePath.c_str())) { return strFilePath; } else { return ""; } } else { delete[] pBuffer; pBuffer = NULL; pHttpFile->Close(); //delete pHttpFile; sess.Close(); ZTools::WriteZToolsFormatLog("本地文件%s打开出错", strFilePath.c_str()); return ""; } } else { delete[] pBuffer; pBuffer = NULL; pHttpFile->Close(); //delete pHttpFile; sess.Close(); ZTools::WriteZToolsFormatLog("打开网页文件出错,错误码:%d", dwStatus); return ""; } delete[] pBuffer; pBuffer = NULL; pHttpFile->Close(); //delete pHttpFile; sess.Close(); return ""; }
bool CMainDlg::GetUrlServer() { m_mapUrl.clear(); CString url(_T("http://139.129.60.122/UpData/forumupdata.json")); CInternetSession session; std::string strHtml; try { CHttpFile* pfile = (CHttpFile*)session.OpenURL(url,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()) { CStdioFile myFile; CString strLine; string strpath = theApp.m_strInsPath; strpath +="\\polopointsUpdate.json"; if(myFile.Open((LPCTSTR)(LPSTR)strpath.c_str(), CFile::modeRead)) { while(myFile.ReadString(strLine)) { strHtml +=strprintf("%s",strLine); } //读取 myFile.Close(); }else{ return false; } }else{ //创建 CStdioFile File; string strpath = theApp.m_strInsPath; strpath +="\\polopointsUpdate.json"; File.Open((LPCTSTR)(LPSTR)strpath.c_str(),CFile::modeWrite | CFile::modeCreate); File.WriteString(strHtml.c_str()); File.Close(); } Json::Reader reader; Json::Value root; if (reader.parse(strHtml, root)) { if (!root.isObject()) { return false; } Json::Value rootcn = root["Chinese"]; if (rootcn.isNull()&& !rootcn.isArray()) { return false; } int index = rootcn.size(); for (int i = 0;i <index;i++) { Json::Value msgroot = rootcn[i]; Json::Value value = msgroot["msn"]; if (value.isNull()) { return false; } CString key = msgroot["msn"].asCString(); value = msgroot["url"]; if (value.isNull()) { return false; } CString valuetemp = msgroot["url"].asCString(); m_mapUrl[key] = valuetemp; } return true; } return false; }