Ejemplo n.º 1
3
UINT CMMSSender::PostHTTP(CString csURL, BYTE* strPostData, long lDataSize, CString csHeaders, CString& csRetHeaders, CString& csRetData)
{
	UINT nCode=0;

	DWORD dwService;
	CString csServer;
	CString csPath;
	INTERNET_PORT nPort;
	CString csUser;
	CString csPwd;
	AfxParseURLEx(csURL,dwService,csServer,csPath,nPort,csUser,csPwd,0);

	CHttpConnection* pConnection = NULL;
	pConnection=m_pSession->GetHttpConnection(csServer,0, nPort, NULL, NULL);

	if(pConnection)
	{
		BOOL bResult=FALSE;
		CHttpFile* pFile = NULL;
		pFile=pConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST,csPath,NULL,1,NULL,"HTTP/1.1",INTERNET_FLAG_NO_AUTO_REDIRECT);

		if(pFile)
		{
			try
			{
				bResult=pFile->SendRequest(csHeaders, strPostData, lDataSize);
				if(bResult)
				{
					CString csCode;
					pFile->QueryInfo(HTTP_QUERY_STATUS_CODE,csCode);
					nCode=atoi(csCode);

					CString csHeaders;
					pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF,csRetHeaders);

					csRetData=ReadData(pFile);
				}
			}
			catch(CInternetException* e)
			{
			}

			pFile->Close();
			delete pFile;
		}
		pConnection->Close();
		delete pConnection;
	}

	return nCode;
}
Ejemplo n.º 2
0
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;

}
Ejemplo n.º 3
0
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;
}
	ERMsg GetPageText(CHttpConnectionPtr& pConnection, const std::string& URLIn, std::string& text, bool bConvert, DWORD flags)
	{
		
		ERMsg msg;

		//std::string text;
		//INTERNET_FLAG_NO_COOKIES|
		CString URL = WBSF::convert(URLIn).c_str();
		CHttpFile* pURLFile = pConnection->OpenRequest(_T("GET"), URL, NULL, 1, NULL, NULL, flags);

		bool bRep = false;

		if( pURLFile!=NULL )
		{
			int nbTry=0;
			while( !bRep && msg)
			{
				TRY
				{
					nbTry++;
					bRep = pURLFile->SendRequest()!=0;
				}
				CATCH_ALL(e)
				{
					DWORD errnum = GetLastError();
					if( errnum ==12002 ||errnum==12029)
					{
						if( nbTry >= 10)
						{
							msg = UtilWin::SYGetMessage(*e);
						}
						//try again
					}
					else if(  errnum == 12031 || errnum == 12111) 
					{
						//throw a exception: server reset
						THROW( new CInternetException(errnum));
					}
					else if( errnum ==12003)
					{
						msg = UtilWin::SYGetMessage(*e);

						DWORD size = 255;
						TCHAR cause[256]={0};
						InternetGetLastResponseInfo( &errnum, cause, &size);
						if (_tcslen(cause) > 0)
							msg.ajoute(UtilWin::ToUTF8(cause));
					}
					else
					{
						CInternetException e(errnum);
						msg += UtilWin::SYGetMessage(e);
					}
				}
				END_CATCH_ALL
			}
		}
Ejemplo n.º 5
0
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);
	}
}
Ejemplo n.º 6
0
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;
}
Ejemplo n.º 7
0
UINT CCopiagenda::GetHTTPS(CString csURL, CString csHeaders, CString& csRetHeaders, CString& csRetData)
{
	UINT nCode;

	DWORD dwService;
	CString csServer;
	CString csPath;
	INTERNET_PORT nPort;
	CString csUser;
	CString csPwd;
	AfxParseURLEx(csURL,dwService,csServer,csPath,nPort,csUser,csPwd,0);

	CHttpConnection* pConnection = NULL;
	pConnection=m_pSession->GetHttpConnection(csServer,INTERNET_FLAG_RELOAD|INTERNET_FLAG_DONT_CACHE|INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_SECURE,nPort, NULL, NULL);

	if(pConnection)
	{
		BOOL bResult=FALSE;
		CHttpFile* pFile = NULL;
		pFile=pConnection->OpenRequest(CHttpConnection::HTTP_VERB_GET,csPath,NULL,1,NULL,"HTTP/1.1",INTERNET_FLAG_EXISTING_CONNECT|INTERNET_FLAG_RELOAD|INTERNET_FLAG_DONT_CACHE|INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_NO_AUTO_REDIRECT|INTERNET_FLAG_SECURE);

		if(pFile)
		{
			try
			{
				bResult=pFile->SendRequest(csHeaders, NULL, 0);
				if(bResult)
				{
					CString csCode;
					pFile->QueryInfo(HTTP_QUERY_STATUS_CODE,csCode);
					nCode=atoi(csCode);

					pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF,csRetHeaders);

					csRetData=ReadData(pFile);
				}
			}
			catch(CInternetException* e)
			{
			}

			pFile->Close();
			delete pFile;
		}

		pConnection->Close();
		delete pConnection;
	}

	return nCode;
}
Ejemplo n.º 8
0
DWORD CLoginDlg::userProfile(LPCTSTR serverURL, LPCTSTR requestPage)
{

#ifdef _HTTPS
	CInternetSession session(_T("HelloChat"), INTERNET_FLAG_SECURE);
	CHttpConnection* pConnection = session.GetHttpConnection(serverURL, INTERNET_SERVICE_HTTP, INTERNET_DEFAULT_HTTPS_PORT);
	CString strToken = L"token:";
	strToken = strToken + m_strMyToken + L"\r\n";
	CHttpFile* pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_GET, requestPage, NULL, 1, NULL, NULL, INTERNET_FLAG_SECURE | INTERNET_FLAG_RELOAD |
		INTERNET_FLAG_DONT_CACHE |
		INTERNET_FLAG_NO_COOKIES);
#else
	CInternetSession session(_T("HelloChat"), PRE_CONFIG_INTERNET_ACCESS);
	CHttpConnection* pConnection = session.GetHttpConnection(serverURL);
	CString strToken = L"token:";
	//strToken = strToken + m_strToken + L"\r\n";
	strToken = strToken + m_strMyToken + L"\r\n";
	CHttpFile* pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_GET, requestPage, NULL, 1, NULL, NULL, INTERNET_FLAG_RELOAD |
		INTERNET_FLAG_DONT_CACHE |
		INTERNET_FLAG_NO_COOKIES);
#endif

	VERIFY(pFile->AddRequestHeaders(HEADER));
	VERIFY(pFile->AddRequestHeaders(strToken));
	VERIFY(pFile->SendRequest());

	// GET POST STATUS 
	DWORD dwPostStatus = 0;
	VERIFY(pFile->QueryInfoStatusCode(dwPostStatus));
	
	CString strBuffer = L"";
	BOOL brtn = pFile->ReadString(strBuffer);
	char* rtnBuffer = LPSTR(LPCTSTR(strBuffer));

	if (dwPostStatus == HTTP_STATUS_OK)
	{	
		BOOL bRtn = dataParser(rtnBuffer);
		if (!bRtn){
			AfxMessageBox(L"User Info Paser Error");
		}
	}
	else{
		CComm func;
		func.WriteErrorLog(rtnBuffer);
	}
	pFile->Close();

	return dwPostStatus;
}
Ejemplo n.º 9
0
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;
}   
Ejemplo n.º 10
0
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();
}
Ejemplo n.º 11
0
/*
 * 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;
}
Ejemplo n.º 12
0
/* ===================================================================
*         GET Tally TB Response for a given request
*  ===================================================================
*/
BOOL CTallyExporterDlg::GetTallyTBResponse(CString& xmlTBRequestRef,vector<string>& allRowsOfTBRef, int port)
{
   CInternetSession session(_T("TB Session"));
   CHttpConnection* pServer = NULL;
   CHttpFile* pFile = NULL;   

   try
   {
      CString strServerName;
      DWORD dwRet = 0;
	  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)xmlTBRequestRef, xmlTBRequestRef.GetLength());
      pFile->QueryInfoStatusCode(dwRet);

	  CString csvLinesToBeRead;
	  CString& csvLinesToBeReadRef = csvLinesToBeRead;
      if (dwRet == HTTP_STATUS_OK)
      {
         while (pFile->ReadString(csvLinesToBeReadRef) == TRUE)
         {			 
			 allRowsOfTBRef.push_back((LPCTSTR)csvLinesToBeReadRef);
         }
      }
	  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;
}
Ejemplo n.º 13
0
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;
}
Ejemplo n.º 14
0
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();
}
Ejemplo n.º 15
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;

}
	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;
	}
CString CHttpRequest::Download (CString strURL, int nMethod, CString strHeaders, CString strData,
	CString strFilename,
	bool* pbCancelDownload, DWORD dwDownloadId, int& nError, int nApproxContentLength,									   
	HWND hwndProgress, HWND hwndStatus, CString strMsg)
{
	gl_stkDownloads.push_back (dwDownloadId);

	bool bUseFile = !strFilename.IsEmpty ();
	strStatusMsg = bUseFile ? strFilename : strMsg;

	// show the UI controls
	if (dwDownloadId == gl_stkDownloads.back ())
	{
		if (hwndProgress != NULL)
		{
			::PostMessage (hwndProgress, PBM_SETPOS, 0, 0);
			::ShowWindow (hwndProgress, SW_SHOW);
		}

		if (hwndStatus != NULL)
			::PostMessage (hwndStatus, SB_SETTEXT, 1, (LPARAM) strStatusMsg.GetBuffer (0));
	}

	/*
	CString strDisplayFilename, strDisplay;
	if (!strFilename.IsEmpty () && (pStatus != NULL))
	{
		strcpy (strDisplayFilename.GetBuffer (strFilename.GetLength () + 1), strFilename.GetBuffer (0));
		strDisplayFilename.ReleaseBuffer ();

		// needs ellipsis?
		CRect r;
		pStatus->GetWindowRect (&r);
		r.right -= 300;
		HDC hdc = ::GetWindowDC (pStatus->GetSafeHwnd ());
		::DrawText (hdc, strDisplayFilename, -1, &r, DT_PATH_ELLIPSIS | DT_MODIFYSTRING);
		::ReleaseDC (pStatus->GetSafeHwnd (), hdc);
	}*/

	CHttpConnection* pHttpConnection = NULL;
	CHttpFile* pHttpFile = NULL;
	LPVOID lpvoid = NULL;

	DWORD dwServiceType;
	CString strServer, strObject;
	INTERNET_PORT nPort;
	AfxParseURL (strURL, dwServiceType, strServer, strObject, nPort);

	// declare CMyInternetSession object
	CInternetSession InternetSession (NULL,
		//"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; (R1 1.3))",
		1, INTERNET_OPEN_TYPE_PRECONFIG);

	CString strRetData;

	try
	{
		// establish the HTTP connection
		pHttpConnection = InternetSession.GetHttpConnection (strServer, nPort, "", "");

		// open the HTTP request
		pHttpFile = pHttpConnection->OpenRequest (nMethod, strObject, NULL, 1, NULL,
			NULL, INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_NO_AUTO_REDIRECT | INTERNET_FLAG_TRANSFER_BINARY);

		if (pHttpFile->SendRequest (strHeaders, strHeaders.GetLength (),
			static_cast<void*>(strData.GetBuffer (0)), strData.GetLength ()))
		{
			DWORD dwRet;
			// query the HTTP status code
			pHttpFile->QueryInfoStatusCode (dwRet);
			if (dwRet >= 400)
			{
				nError = dwRet;
				gl_stkDownloads.remove (dwDownloadId);
				return "";
			}
			
			CString strContentLen;
			LPSTR lpszResult = NULL;
			UINT nRead = 0, nTotalRead = 0;

			lpvoid = malloc (HTTPFILE_BUFFLEN);
			// memory error
			if (!lpvoid)
			{
				AfxMessageBox("Error allocating memory");
				if (pHttpConnection)
				{
					pHttpConnection->Close();
					delete pHttpConnection;
				}
				if (pHttpFile)
				{
					pHttpFile->Close();
					delete pHttpFile;
				}
				nError = -1;
				gl_stkDownloads.remove (dwDownloadId);
				return "";
			}

			CFile f1;

			DWORD dwSize;
			if (!pHttpFile->QueryInfo (HTTP_QUERY_CONTENT_LENGTH, dwSize))
				dwSize = nApproxContentLength;
			if ((dwDownloadId == gl_stkDownloads.back ()) && (hwndProgress != NULL))
				::PostMessage (hwndProgress, PBM_SETRANGE32, 0, dwSize);

			if (bUseFile)
				if (!f1.Open (strFilename, CFile::modeCreate | CFile::modeWrite))
				{
					nError = -1;
					gl_stkDownloads.remove (dwDownloadId);
					return "";
				}

			DWORD dwStart = GetTickCount ();

			// read the HTTP response
			while (nRead = pHttpFile->Read ((byte*) lpvoid + (bUseFile ? 0 : nTotalRead), HTTPFILE_BUFFLEN))
			{
				if (pbCancelDownload != NULL)
					if (*pbCancelDownload)
					{
						// download cancelled
						if (pHttpConnection)
						{
							pHttpConnection->Close();
							delete pHttpConnection;
						}
						if (pHttpFile)
						{
							pHttpFile->Close();
							delete pHttpFile;
						}

						// delete the file
						if (bUseFile)
						{
							f1.Close ();
							CFile::Remove (strFilename);
						}

						nError = -1;
						gl_stkDownloads.remove (dwDownloadId);
						return "";
					}

				nTotalRead += nRead;

				// store the data
				if (bUseFile)
					f1.Write (lpvoid, nRead);
				else
				{
					lpvoid = realloc (lpvoid, nTotalRead + HTTPFILE_BUFFLEN);
					if (!lpvoid)
					{
						AfxMessageBox ("Error allocating memory");
						if (pHttpConnection)
						{
							pHttpConnection->Close();
							delete pHttpConnection;
						}
						if (pHttpFile)
						{
							pHttpFile->Close();
							delete pHttpFile;
						}

						nError = -1;
						gl_stkDownloads.remove (dwDownloadId);
						return "";
					}
				}

				// UI Feedback
				if (dwDownloadId == gl_stkDownloads.back ())
				{
					// update progress control
					if (hwndProgress != NULL)
						::PostMessage (hwndProgress, PBM_SETPOS, nTotalRead, 0);

					if (hwndStatus != NULL)
					{
						strKB.Format (IDS_DOWNLOADSTATUS_KB,
							nTotalRead / 1024,			// KBs read
							dwSize / 1024);				// Total size (KBs)
						::PostMessage (hwndStatus, SB_SETTEXT, 2, (LPARAM) strKB.GetBuffer (0));

						// percentage
						if (dwSize != 0)
						{
							strPercent.Format (IDS_DOWNLOADSTATUS_PERCENT, nTotalRead * 100 / dwSize);
							::PostMessage (hwndStatus, SB_SETTEXT, 3, (LPARAM) strPercent.GetBuffer (0));
						}

						// KB/s
						strKBs.Format (IDS_DOWNLOADSTATUS_KBS, (double) nTotalRead / 1024.0 / ((GetTickCount () - dwStart) / 1000.0 + 1));
						::PostMessage (hwndStatus, SB_SETTEXT, 4, (LPARAM) strKBs.GetBuffer (0));
					}
				}
			}
					
			if (bUseFile)
				f1.Close();
			else
			{
				// get response headers
				LPSTR lpszBuf = strRetData.GetBuffer (nTotalRead + HTTPFILE_BUFFLEN);
				DWORD dwBufLen = HTTPFILE_BUFFLEN;
				pHttpFile->QueryInfo (HTTP_QUERY_RAW_HEADERS_CRLF, lpszBuf, &dwBufLen);

				// copy contents
				*((LPSTR) lpvoid + nTotalRead) = 0;
				strcpy (lpszBuf + dwBufLen - 1, (LPSTR) lpvoid);

				strRetData.ReleaseBuffer ();
			}
		}
	}
	catch(CInternetException *e)
	{
		//e->ReportError();
		char szError[1001];
		e->GetErrorMessage (szError, 1000);
		CString strMsg;
		strMsg.Format (IDS_ERROR_HTTPREQUEST, strURL.GetBuffer (-1), szError);
		AfxMessageBox (strMsg, MB_ICONEXCLAMATION);

		e->Delete();
	}

	// cleanup
	if (lpvoid)
		free (lpvoid);

	if (pHttpFile)
	{
		pHttpFile->Close();
		delete pHttpFile;
	}
	if (pHttpConnection)
	{
		pHttpConnection->Close();
		delete pHttpConnection;
	}

	// hide UI controls
	if (dwDownloadId == gl_stkDownloads.back ())
	{
		if (hwndProgress != NULL)
			::ShowWindow (hwndProgress, SW_HIDE);
		if (bUseFile)
			if (hwndStatus != NULL)
				for (int i = 1; i <= 4; i++)
					::PostMessage (hwndStatus, SB_SETTEXT, i, (LPARAM) "");
	}

	gl_stkDownloads.remove (dwDownloadId);
	return strRetData;
}
Ejemplo n.º 18
0
//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;
}
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;
}
Ejemplo n.º 20
0
void CHttpClient::DoOpenURL( LPCTSTR lpszURL, DWORD dwHttpRequestFlags,
							CString &strHeader, CString &strPostData,
							CInternetSession *pSession,
							CHttpConnection **ppServer, CHttpFile **ppFile,
							PROGRESS_CALLBACK fnCallback, void * cookie )
{
	CString strServerName;
	CString strObject;
	INTERNET_PORT nPort;
	DWORD dwServiceType;
	
	int nVerb = (strPostData.GetLength()>0 ? CHttpConnection::HTTP_VERB_POST : CHttpConnection::HTTP_VERB_GET);

	if (!AfxParseURL(lpszURL, dwServiceType, strServerName, strObject, nPort) ||
		dwServiceType != INTERNET_SERVICE_HTTP)
	{
		ThrowTearException( ERR_TEAR_URLFORMAT );
	}

	if( fnCallback )
		fnCallback( PROG_HTTPCONNECTTING, 0, NULL, cookie );

	CHttpConnection *pServer = pSession->GetHttpConnection(strServerName, dwHttpRequestFlags, nPort, m_strProxyUser, m_strProxyPasswd );
	CHttpFile	* pFile = pServer->OpenRequest(nVerb, strObject, NULL, 1, NULL, NULL, dwHttpRequestFlags);
	pFile->AddRequestHeaders(strHeader, HTTP_ADDREQ_FLAG_COALESCE);
	if( strPostData.GetLength() > 0 ) // post
	{
		try
		{
			pFile->SendRequestEx( DWORD(strPostData.GetLength()) );
			pFile->WriteString(strPostData);
			pFile->EndRequest();
		}
		catch( CInternetException *pp )	// HTTP_STATUS_BAD_METHOD
		{
			pp->Delete();

			// close up the redirected site
			pFile->Close();
			delete pFile;
			pFile	=	NULL;
			pServer->Close();
			delete pServer;
			pServer	=	NULL;

			pServer = pSession->GetHttpConnection(strServerName, dwHttpRequestFlags, nPort, m_strProxyUser, m_strProxyPasswd );
			pFile = pServer->OpenRequest(nVerb, strObject, NULL, 1, NULL, NULL, dwHttpRequestFlags);
			pFile->AddRequestHeaders(strHeader, HTTP_ADDREQ_FLAG_COALESCE);
			pFile->SendRequestEx( DWORD(strPostData.GetLength()) );
			pFile->WriteString(strPostData);
			pFile->EndRequest();
		}
	}
	else
	{
		pFile->SendRequest();
	}

	if( fnCallback )
		fnCallback( PROG_REQUESTSENT, 0, NULL, cookie );

	// Bad Post method
	DWORD dwRet	=	0;
	pFile->QueryInfoStatusCode( dwRet );

	// if access was denied, prompt the user for the password
	if (dwRet == HTTP_STATUS_DENIED
		|| dwRet == HTTP_STATUS_PROXY_AUTH_REQ )
	{
		DWORD dwPrompt;
		dwPrompt = pFile->ErrorDlg(NULL, ERROR_INTERNET_INCORRECT_PASSWORD,
			FLAGS_ERROR_UI_FILTER_FOR_ERRORS | 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)
			ThrowTearException( ERR_TEAR_CANCEL );
		if( strPostData.GetLength() > 0 ) // post
		{
			try{
				pFile->SendRequestEx( DWORD(strPostData.GetLength()) );
				pFile->WriteString(strPostData);
				pFile->EndRequest();
			}
			catch( CInternetException *pp ) // HTTP_STATUS_BAD_METHOD
			{
				pp->Delete();

				pFile->SendRequestEx( DWORD(strPostData.GetLength()) );
				pFile->WriteString(strPostData);
				pFile->EndRequest();
			}
		}
		else
		{
			pFile->SendRequest();
		}
		pFile->QueryInfoStatusCode(dwRet);
	}

	if( dwRet == HTTP_STATUS_BAD_METHOD )
	{
		// close up the redirected site
		pFile->Close();
		delete pFile;
		pFile	=	NULL;
		pServer->Close();
		delete pServer;
		pServer	=	NULL;

		pServer = pSession->GetHttpConnection(strServerName, dwHttpRequestFlags, nPort, m_strProxyUser, m_strProxyPasswd );
		pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject, NULL, 1, NULL, NULL, dwHttpRequestFlags);
		pFile->AddRequestHeaders(strHeader, HTTP_ADDREQ_FLAG_COALESCE);
		if( strPostData.GetLength() > 0 ) // post
		{
			pFile->SendRequestEx( DWORD(strPostData.GetLength()) );
			pFile->WriteString(strPostData);
			pFile->EndRequest();
		}
		else
		{
			pFile->SendRequest();
		}
	}

	*ppServer	=	pServer;
	*ppFile	=	pFile;
}
Ejemplo n.º 21
0
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;
}
Ejemplo n.º 22
0
int CHttpRequest::ConnectUrl(TCHAR *sUrl, TCHAR *sReturn, long *lVersion, int *Count)
{
	ODS(_T("XFILTER.EXE: GetFromUrl Begin... \n"));
	
	if(sUrl == NULL)
		return XERR_INVALID_PARAMETER;

	CString			strServerName;
	CString			strObject;
	INTERNET_PORT	nPort;
	DWORD			dwServiceType;

	if (!AfxParseURL(sUrl, dwServiceType, strServerName, strObject, nPort) ||
		dwServiceType != INTERNET_SERVICE_HTTP)
	{
		ODS(_T("XFILTER.EXE: Internet Invalid Url ..."));
		return XERR_INTERNET_URL_ERROR;
	}

	CInternetSession	session(GUI_APP_CLASS_NAME);
	CHttpConnection		*pServer	= NULL;
	CHttpFile			*pFile		= NULL;
	int					iRet		= XERR_SUCCESS;

	m_IsConnecting = TRUE;

	try
	{
		pServer = session.GetHttpConnection(strServerName, nPort);
		pFile	= pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject);

		pFile->AddRequestHeaders(szHeaders);
		pFile->SendRequest();

		DWORD	dwRet;
		pFile->QueryInfoStatusCode(dwRet);

		if (dwRet >= 400 && dwRet <= 499)
		{
			ODS(_T("XFILTER.EXE: Internet Request Error ..."));
			iRet = XERR_INTERNET_REQUEST_ERROR;
		}
		else if(dwRet >= 500 && dwRet <= 599)
		{
			ODS(_T("XFILTER.EXE: Internet Server Error ..."));
			iRet = XERR_INTERNET_SERVER_ERROR;
		}
		else if(sReturn != NULL)
		{
			pFile->ReadString(sReturn, MAX_NET_COMMAND_LENTH - 1);
			ODS(sReturn);

			CString tmpStr	= sReturn;
			long lVer		= atol(tmpStr.Left(MAX_NET_COMMAND_VERSION_LENTH));

			if(lVer > *lVersion)
			{
				*lVersion = lVer;
				int		i = 1;

				while (i < MAX_NET_COMMAND
					&& pFile->ReadString((sReturn + MAX_NET_COMMAND_LENTH * i), MAX_NET_COMMAND_LENTH - 1))
				{
					ODS(sReturn + i * MAX_NET_COMMAND_LENTH);
					i ++;
				}
				*Count = i;
			}
			else
			{
				*Count = 1;
			}
		}
		else
		{
			CString sRet;
			pFile->ReadString(sRet);
			if(sRet.GetAt(0) != '1')
				iRet = XERR_INTERNET_REG_ERROR;

			ODS2(_T("XFILTER.EXE: Internet User Register Return Value "),sRet);
		}

		pFile->Close();
		pServer->Close();
	}
	catch(CInternetException* pEx)
	{
		pEx->Delete();
		iRet = XERR_INTERNET_CONNECT_ERROR;
		ODS(_T("XFILTER.EXE: GetFromUrl XERR_INTERNET_CONNECT_ERROR... "));
	}

	if (pFile != NULL)
		delete pFile;
	if (pServer != NULL)
		delete pServer;
	session.Close();

	m_IsConnecting = FALSE;

	ODS(_T("XFILTER.EXE: GetFromUrl End... "));
	return iRet;
}
Ejemplo n.º 23
0
string GetData(const char * url, const string referer) 
{

	CInternetSession session("Mozilla/4.0");
	session.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 10*1000);
	CHttpConnection * pServer = NULL;
	CHttpFile* pFile = NULL;
	bool bProgressMode = false; 
	bool bStripMode = false; 
	string line = "";

	try {
		CString strServerName; 
		CString strObject; 
		INTERNET_PORT nPort; 
		DWORD dwServiceType; 

		if (!AfxParseURL(url, dwServiceType, strServerName, strObject, nPort) || 
		dwServiceType != INTERNET_SERVICE_HTTP) 
		{ 
			TRACE( _T("Error: can only use URLs beginning with http://") );
			return "request failed - can only use URLs beginning with http://";
		} 

		if (bProgressMode) 
		{ 
			TRACE("Opening Internet...%s\n", url);
			VERIFY(session.EnableStatusCallback(TRUE)); 
		} 
		
		pServer = session.GetHttpConnection(strServerName, 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 > (int)file.length()) file_start = -1;
		}
		if(file_start > 0) file = file.substr(file_start);
		else file = "";
		LPCTSTR ref = NULL;
		if(referer != "") ref = referer.c_str();
 		pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET,file.c_str(), ref); 

		SetCookie(&session, url); 

		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 diaTRACE, bail out 

			if (dwPrompt != ERROR_INTERNET_FORCE_RETRY) 
			{ 
				TRACE( _T("Access denied: Invalid password"));
				return "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") );
				return "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.") );
				return "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.") );
				return "request failed - the redirected URL does not reference a HTTP resource";
			} 

			// try again at the new location 
			pServer = session.GetHttpConnection(strServerName, nPort); 
			pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject);
			pFile->SendRequest(); 

			pFile->QueryInfoStatusCode(dwRet); 
			if (dwRet != HTTP_STATUS_OK) 
			{ 
				//TRACE( _T("Error: Got status code ") dwRet );
				return "request failed - Got status code " + dwRet;
			} 
		}

		TCHAR sz[1024]; 
		sz[1023] = 0;
		while (pFile->ReadString(sz, 1023)) 
		{ 
			line += sz;
		} 	
		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(error);
		}
		e->Delete();
		e = NULL;
		line = "request failed - status code N/A";
	}
	if(pServer != NULL) {
		pServer->Close();
		delete pServer;
		pServer = NULL;
	}
	if(pFile != NULL) {
		pFile->Close();
		delete pFile;
		pFile = NULL;
	}
	return line;

}
Ejemplo n.º 24
0
//负责接收上传操作的页面的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;
}
Ejemplo n.º 25
0
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;
}
Ejemplo n.º 26
0
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;
}
Ejemplo n.º 27
0
DWORD CLoginDlg::login(LPCTSTR serverURL, LPCTSTR requestPage, LPCTSTR formData)
{


#ifdef _HTTPS
	CInternetSession session(_T("HelloChat"), INTERNET_FLAG_SECURE);
	CHttpConnection* pConnection = session.GetHttpConnection(serverURL, INTERNET_SERVICE_HTTP, INTERNET_DEFAULT_HTTPS_PORT);
	CString strHeaders = HEADER;
	// OPEN A POST REQUEST 
	CHttpFile* pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST, requestPage, NULL, 1, NULL, NULL, INTERNET_FLAG_SECURE | INTERNET_FLAG_RELOAD |
		INTERNET_FLAG_DONT_CACHE |
		INTERNET_FLAG_NO_COOKIES);
#else
	CInternetSession session(_T("HelloChat"), PRE_CONFIG_INTERNET_ACCESS);
	CHttpConnection* pConnection = session.GetHttpConnection(serverURL);
	CString strHeaders = HEADER;
	// OPEN A POST REQUEST 
	CHttpFile* pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST, requestPage, NULL, 1, NULL, NULL, INTERNET_FLAG_RELOAD |
		INTERNET_FLAG_DONT_CACHE |
		INTERNET_FLAG_NO_COOKIES);
#endif
	
	// UNICODE 
#if defined(_UNICODE) 
	// Length of form data (including '\\0') 
	const int dwLength = _tcslen(formData) + 1;
	// Alocate ANSI character array 
	char *lpFormData = new char[dwLength];
	// Convert wide char form data to ANSI 
	//멀티바이트코드로 변환.
	VERIFY(0 != ::WideCharToMultiByte(CP_ACP, 0, formData, -1, lpFormData, dwLength, 0, 0));
	// Send the request to the HTTP server 
	VERIFY(pFile->SendRequest(strHeaders, lpFormData, dwLength));
	
	//  Delete ANSI array 
	delete[] lpFormData;
	// ANSI 
#else 
	// Send the request to the HTTP server 
	VERIFY(pFile->SendRequest(strHeaders, (LPVOID)formData, strlen(formData)));
#endif 
	// GET POST STATUS 
	DWORD dwPostStatus = 0;
	VERIFY(pFile->QueryInfoStatusCode(dwPostStatus));

	CString strBuffer = L"";
	BOOL brtn = pFile->ReadString(strBuffer);
	char* szBuff = LPSTR(LPCTSTR(strBuffer));
	
	if (dwPostStatus == HTTP_STATUS_OK)
	{
		// 토큰 획득.
		BOOL bRtn = getToken(szBuff);
		if (!bRtn){
			//토큰 획득 실패시.
			dwPostStatus = HTTP_STATUS_NO_CONTENT;

			//토큰 획득 실패 메시지
			CComm func;
			func.WriteErrorLog(szBuff);
		}
	}
	else if (dwPostStatus == HTTP_STATUS_DENIED){
		//토큰 Expire 확인.
		CComm func;
		BOOL bRtn = func.isTokenExpire(szBuff);
		if (bRtn){
			//토큰 만료에 대한 로그 작성
			func.WriteErrorLog(szBuff);

			// 토큰 Expire  토큰 재발급.
			GetPrivateProfileString(L"MYINFO", L"token", L"", (LPWSTR)func.m_myInfo.token, sizeof(func.m_myInfo.token), func.m_strINI);
			m_strMyToken = (LPCTSTR)(LPWSTR)func.m_myInfo.token;
			DWORD dwRtn = func.TokenRefresh(m_strMyToken);
			if (dwRtn == HTTP_STATUS_OK){
				//토큰은 다시 재 발급 받았으므로 로그인 다시 시도 메시지.
				AfxMessageBox(L"Token Expired\r\nLogin Again");
			}
			else{
				//토큰 재 발급 과정에서 재 발급 실패.
				AfxMessageBox(L"Token Refresh Fail.");
			}
		}
	}
	
	pFile->Close();

	return dwPostStatus;
}
Ejemplo n.º 28
0
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;
}
Ejemplo n.º 29
0
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;
}
Ejemplo n.º 30
0
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;
    //}
}