예제 #1
0
BOOL CProxyIP::GetFirstGoalUrl(const TCHAR* pSrcUrl, TCHAR* pGoalUrl)
{
    BOOL bRet = FALSE;
    CHttpFile* pHttpFile = (CHttpFile *)m_pSession->OpenURL(pSrcUrl);
    DWORD dwStatusCode = 0;
    pHttpFile->QueryInfoStatusCode(dwStatusCode);
    if (dwStatusCode == HTTP_STATUS_OK)
    {
        CString strData;
        wstring subStr = _T("国内网页http代理ip地址服务器");
        while(pHttpFile->ReadString(strData))
        {
            TCHAR mainStr[MAX_STR_LEN] = {0};
            ConvertMultiByteToWideChar((char *)strData.GetBuffer(), mainStr, MAX_STR_LEN);
            wstring wMainStr = mainStr;
            if (wMainStr.find(subStr) < wMainStr.length())
            {
                int startLoc = wMainStr.find(_T("href"));
                int endLoc = wMainStr.find(_T("title"));
                endLoc -= 2;
                startLoc += 6;
                wstring wTempUrl = wMainStr.substr(startLoc, endLoc-startLoc).c_str();
                wmemcpy(pGoalUrl, wTempUrl.c_str(), wcslen(wTempUrl.c_str())+1);
                bRet = TRUE;
                break;
            }
        }
    }
    pHttpFile->Close();
    delete pHttpFile;
    return bRet;
}
예제 #2
0
int CXCCRA2MapUpdaterApp::download_update(string link, string fname)
{
	int error = 0;
	CInternetSession is;
	CHttpFile* f = reinterpret_cast<CHttpFile*>(is.OpenURL(link.c_str(), INTERNET_FLAG_TRANSFER_BINARY));
	if (!f)
		error = 1;
	else 
	{
		Cvirtual_file h;
		DWORD status;
		if (!f->QueryInfoStatusCode(status))
			error = 2;
		else if (status != 200)
			error = 3;
		else
		{
			int total_size = f->Seek(0, CFile::end);
			f->Seek(0, CFile::begin);
			Cdownload_dlg dlg;
			dlg.set(link, fname, total_size);
			dlg.Create(Cdownload_dlg::IDD, NULL);
			dlg.EnableWindow(false);
			Cvirtual_binary t;
			while (!error)
			{
				int cb_p = min<int>(f->GetLength(), 1 << 10);
				if (!cb_p)
					break;
				f->Read(t.write_start(cb_p), cb_p);
				h.write(t);
				dlg.set_size(h.size());
				dlg.UpdateWindow();
			}
			h.compact();
			Cxif_key k;
			if (k.load_key(h.data(), h.size()))
				error = 5;
			else
			{
				for (t_xif_key_map::const_iterator ki = k.m_keys.begin(); ki != k.m_keys.end(); ki++)
				{
					if (error)
						break;
					const Cxif_key& l = ki->second;
					string fext = boost::to_lower_copy(Cfname(l.get_value_string(vi_fname)).get_fext());
					if (fext != ".mmx"
						&& (fext != ".yro") || !Cfname(xcc_dirs::get_exe(game_ra2_yr)).exists())
						continue;
					if (file32_write(Cfname(fname).get_path() + l.get_value_string(vi_fname), l.get_value(vi_fdata).get_data(), l.get_value(vi_fdata).get_size()))
						error = 6;
				}
			}
			dlg.DestroyWindow();
		}
		f->Close();
	}
	return error;
}
예제 #3
0
void CHttpPostDlg::OnBtnSendpost() 
{
	CInternetSession m_InetSession(_T("session"),
		0,
		INTERNET_OPEN_TYPE_PRECONFIG,
		NULL,
		NULL,
		INTERNET_FLAG_DONT_CACHE);     //设置不缓冲
	CHttpConnection* pServer = NULL;
	CHttpFile* pFile = NULL;
	CString strHtml = "";
	CString ActionServer = _T("www.cqjg.gov.cn");
	CString strRequest = _T("LicenseTxt=AG8091&VIN=LJDAAA21560205432"); //POST过去的数据
	CString strHeaders = "Accept: text*/*\r\nContent-Type: application/x-www-form-urlencoded\r\nUser-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon;";
	int nRead = 0;
	try
	{
		INTERNET_PORT nPort = 80; //端口
		pServer = m_InetSession.GetHttpConnection(ActionServer, nPort);
		pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST,"/netcar/FindOne.aspx");
		pFile->AddRequestHeaders(strHeaders);
		pFile->SendRequestEx(strRequest.GetLength());
		pFile->WriteString(strRequest); //重要-->m_Request 中有"name=aaa&name2=BBB&..."
		pFile->EndRequest();
		DWORD dwRet;
		pFile->QueryInfoStatusCode(dwRet);
		if (dwRet == HTTP_STATUS_OK)
		{
			CString strLine;
			while ((nRead = pFile->ReadString(strLine))>0)
			{
				strHtml += strLine + "\n";;
			}
		}

		int pos = strHtml.Find(_T("<li class=\"lithreeC\">"));
		if(pos != -1)
		{
			CString Value = strHtml.Mid(pos,500);
			CFile file("test.html",CFile::modeCreate|CFile::modeWrite);
			file.WriteHuge(Value.GetBuffer(0),Value.GetLength());
			file.Close();
			//MessageBox(Value);
		}
		delete pFile;
		delete pServer;
	}
	catch (CInternetException* e)
	{
		char strErrorBuf[255];
		e->GetErrorMessage(strErrorBuf,255,NULL);
		AfxMessageBox(strErrorBuf,MB_ICONINFORMATION);
	}
//	SendPost();
}
예제 #4
0
BOOL CAutoUpdateDlg::DownloadFile(LPCTSTR lpURL,LPCTSTR lpDestFile)
{
	CFile cUdpFile; 
	if(!cUdpFile.Open(lpDestFile,CFile::modeCreate|CFile::modeWrite|CFile::typeBinary|CFile::shareDenyWrite))
		return FALSE;
	BOOL bResult = FALSE;
	CInternetSession sessionDownload;
	try
	{
		CHttpFile* pFile = (CHttpFile*)sessionDownload.OpenURL(lpURL,1,INTERNET_FLAG_TRANSFER_BINARY|INTERNET_FLAG_RELOAD|INTERNET_FLAG_DONT_CACHE);
		CString   query = _T("");
		pFile->QueryInfo(HTTP_QUERY_CONTENT_LENGTH,query);
		long file_len=_ttol(query);
		m_dwTotalSize = file_len;
		PostMessage(WM_POSMESSAGE,0,0);
		DWORD dwStatus;
		if (pFile->QueryInfoStatusCode(dwStatus))
		{
			if (dwStatus == 200)
			{
				pFile->SetReadBufferSize(10240);
				if (TRUE)
				{
					DWORD dwLen = 0;
					char buf[BLOCKSIZE];
					while (TRUE)
					{
						DWORD dwTemp = pFile->Read(buf,BLOCKSIZE);
						if (dwTemp)
						{
							cUdpFile.Write(buf,dwTemp);
						}
						m_dwDownloadedSize += dwTemp;
						PostMessage(WM_POSMESSAGE,0,0);
						if (dwTemp < BLOCKSIZE)
						{
							break;
						}
					}
				}
			}
		}
		pFile->Close();
		bResult = TRUE;
	}
	catch(CInternetException* pException)
	{
		pException->Delete();
		return bResult;
	}
	sessionDownload.Close();
	cUdpFile.Close();
	return bResult;
}
예제 #5
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;
}
예제 #6
0
BOOL CProxyIP::FillGoalUrlVec(const TCHAR* pFirstGoalUrl)
{
    BOOL bRet = FALSE;
    int totalPage = 0;
    CHttpFile* pHttpFile = (CHttpFile *)m_pSession->OpenURL(pFirstGoalUrl);
    DWORD dwStatusCode = 0;
    pHttpFile->QueryInfoStatusCode(dwStatusCode);
    if (dwStatusCode == HTTP_STATUS_OK)
    {
        BOOL bCheck = FALSE;
        CString strData;
        wstring subStrPage = _T("class=\"pagelist\"");
        while(pHttpFile->ReadString(strData))
        {
            TCHAR mainStr[MAX_STR_LEN] = {0};
            ConvertMultiByteToWideChar((char *)strData.GetBuffer(), mainStr, MAX_STR_LEN);
            wstring wMainStr = mainStr;
            if (bCheck)
            {
                int lenn = wMainStr.find(_T("共"));
                wstring wsPage = wMainStr.substr(lenn+1, 1).c_str();
                totalPage = _wtoi(wsPage.c_str());
                bCheck = FALSE;
                break;
            }

            if (wMainStr.find(subStrPage) < wMainStr.length())
            {
                bCheck = TRUE;
            }

        }

        wstring strGoalUrl = pFirstGoalUrl;
        int lenHtml = strGoalUrl.find(_T(".html"));
        wstring newStrGoalUrl = strGoalUrl.substr(0, lenHtml);
        for (int j = 2; j <= totalPage; j++)
        {
            TCHAR tChar[MAX_URL_LEN] = {0};
            swprintf(tChar, MAX_URL_LEN, _T("%s_%d.html"), newStrGoalUrl.c_str(), j);
            m_goalUrlVec.push_back(tChar);
        }
        bRet = TRUE;
    }
    pHttpFile->Close();
    delete pHttpFile;
    return bRet;
}
예제 #7
0
파일: DlgView.cpp 프로젝트: SoyPay/DacrsUI
bool CDlgView::DownLoadFile(const string&UrpPath ,const string& strFilePath)
{
    CInternetSession session;
    std::string strHtml;

    try
    {
        CHttpFile* pfile = (CHttpFile*)session.OpenURL(UrpPath.c_str(),1,INTERNET_FLAG_TRANSFER_ASCII|INTERNET_FLAG_RELOAD,NULL,0);

        DWORD dwStatusCode;
        pfile->QueryInfoStatusCode(dwStatusCode);
        if(dwStatusCode == HTTP_STATUS_OK)
        {
            char strBuff[1025] = {0};
            while ((pfile->Read((void*)strBuff, 1024)) > 0)
            {
                strHtml += strBuff;
            }
        }
        else
        {
            return false;
        }

        pfile->Close();
        delete pfile;
        session.Close();
    }
    catch (CException* e)
    {
        e;//消除警告
        return false;
    }

    if (!strHtml.empty())
    {
        ofstream outfile(strFilePath);
        if (!outfile.is_open())
        {
            return false;
        }
        outfile<<strHtml;
        outfile.close();
    }
    return true;
}
예제 #8
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;
}
/* ===================================================================
*         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;
}
예제 #10
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;
}
예제 #11
0
BOOL CProxyIP::FillIpVec()
{
    int i = 0;
    for (i = 0; i < m_goalUrlVec.size(); i++)
    {
        CHttpFile* pHttpFile = (CHttpFile *)m_pSession->OpenURL(m_goalUrlVec[i].c_str());
        DWORD dwStatusCode = 0;
        pHttpFile->QueryInfoStatusCode(dwStatusCode);
        if (dwStatusCode == HTTP_STATUS_OK)
        {
            BOOL bCheck = FALSE;
            CString strData;
            wstring subStr = _T("class=\"cont_ad\"");
            while(pHttpFile->ReadString(strData))
            {
                TCHAR mainStr[MAX_STR_LEN] = {0};
                ConvertMultiByteToWideChar((char *)strData.GetBuffer(), mainStr, MAX_STR_LEN);
                wstring wMainStr = mainStr;
                if (bCheck)
                {
                    if (wMainStr.find(_T("</span>")) < wMainStr.length())
                    {
                        break;
                    }
                    TCHAR firstPosChar = wMainStr.at(0);
                    if (firstPosChar < 48 || firstPosChar > 57)
                    {
                        continue;
                    }
                    m_IpVec.push_back(wMainStr);
                    m_totalIp++;
                }
                if (wMainStr.find(subStr) < wMainStr.length())
                {
                    bCheck = TRUE;
                }
            }
        }
        pHttpFile->Close();
        delete pHttpFile;
    }
    return TRUE;
}
예제 #12
0
static DWORD WINAPI URLGetAsyncThread( LPVOID lpParam ) 
{
	URLGetAsyncData *data = (URLGetAsyncData *)lpParam;
	if (!data->url.IsEmpty()) {
		CInternetSession session;
		try {
			CHttpFile* pFile;
			pFile = (CHttpFile*)session.OpenURL(data->url, NULL, INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE);
			if (pFile) {
				pFile->QueryInfoStatusCode(data->statusCode);
				CStringA buf;
				char pBuf[256];
				int i;
				do {
					i = pFile->Read(pBuf,255);
					pBuf[i] = 0;
					data->body.AppendFormat("%s",pBuf);
				} while (i>0);
				//--
				pFile->QueryInfo(
					HTTP_QUERY_RAW_HEADERS_CRLF,
					data->headers
					);
				pFile->Close();
			}
			session.Close();
		} catch (CInternetException *e) {
			data->statusCode = 0;
		}
	}
	if (data->message) {
		SendMessage(data->hWnd,data->message,(WPARAM)data,0);
	}
	delete data;
	return 0;
}
예제 #13
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;
}
예제 #14
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;
}
예제 #15
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;
}
예제 #16
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;
}
예제 #17
0
DWORD CHttpClient::Request(LPCTSTR lpszURL, CString &strPostData,
						 CFile *pFileSave, CString *pstrResult,
						 PROGRESS_CALLBACK fnCallback, void *cookie )
{
	DWORD	dwRet	=	HTTP_STATUS_BAD_REQUEST;

	if( NULL == lpszURL || strlen(lpszURL) == 0 )
		return dwRet;

	int	nContentLength = 0;
	int nContentLengthLocal = 0;
	int nContentLengthFinished = 0;
	int nContentLengthTotal = 0;

	// prepare header
	CString	strHeader;
	CMapStringToString	mapHeader;
	if( pFileSave && pFileSave->GetPosition() > 0 )
	{
		nContentLengthFinished = (int)pFileSave->GetPosition();
		CString strRange;
		strRange.Format( "bytes=%u-", nContentLengthFinished );
		mapHeader.SetAt( szRange, strRange );
		
	}
	if( pstrResult && pstrResult->GetLength() > 0 )
	{
		nContentLengthFinished = pstrResult->GetLength();
		CString strRange;
		strRange.Format( "bytes=%u-", nContentLengthFinished );
		mapHeader.SetAt( szRange, strRange );
	}
	if( m_strCookie.GetLength() > 0 )
		mapHeader.SetAt( szCookieKey, m_strCookie );
	MakeHttpHeader( mapHeader, strHeader );

	// default type and flags
	DWORD dwHttpRequestFlags =	INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_RELOAD
								| INTERNET_FLAG_DONT_CACHE
								| INTERNET_FLAG_EXISTING_CONNECT; // | INTERNET_FLAG_KEEP_CONNECTION;
	
	CString	strProxy;
	if( !m_strProxyAddress.IsEmpty() )
		strProxy = FormatProxyString( m_nProxyType, m_strProxyAddress, m_nProxyPort );
	CInternetSession session(	szUserAgentValue, 1, m_nAccessType,
							strProxy, NULL, INTERNET_FLAG_DONT_CACHE );
	// 以下SetOption似乎不起作用
	if( !strProxy.IsEmpty() && !m_strProxyAddress.IsEmpty() )
	{
		session.SetOption( INTERNET_OPTION_PROXY_USERNAME, (LPVOID)(LPCTSTR)m_strProxyUser, m_strProxyUser.GetLength() );
		session.SetOption( INTERNET_OPTION_PROXY_PASSWORD, (LPVOID)(LPCTSTR)m_strProxyPasswd, m_strProxyPasswd.GetLength() );
	}
	session.SetOption( INTERNET_OPTION_RECEIVE_TIMEOUT, 300000 );
	session.SetOption( INTERNET_OPTION_SEND_TIMEOUT, 30000 );
	session.SetOption( INTERNET_OPTION_CONNECT_TIMEOUT, 30000 );

	CHttpConnection* pServer = NULL;
	CHttpFile* pFile = NULL;
	try
	{
		// check to see if this is a reasonable URL
		DoOpenURL( lpszURL, dwHttpRequestFlags, strHeader, strPostData, &session, &pServer, &pFile, fnCallback, cookie );
		if( NULL == pServer || NULL == pFile )
			ThrowTearException( ERR_TEAR_INTERRUPTED );

		pFile->QueryInfoStatusCode(dwRet);

		if (dwRet == HTTP_STATUS_MOVED ||
			dwRet == HTTP_STATUS_REDIRECT ||
			dwRet == HTTP_STATUS_REDIRECT_METHOD)
		{
			CString strNewLocation = GetNewLocation( pFile );

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

			// progress callback
			if( fnCallback )
				fnCallback( PROG_REDIRECTING, 0, NULL, cookie );

			// open new url
			DoOpenURL( strNewLocation, dwHttpRequestFlags,
						strHeader, strPostData,
						&session, &pServer, &pFile, fnCallback, cookie );
			
			pFile->QueryInfoStatusCode(dwRet);
		}

		if (dwRet == HTTP_STATUS_PARTIAL_CONTENT)
			dwRet = HTTP_STATUS_OK;
		if (dwRet != HTTP_STATUS_OK)
			ThrowTearException( ERR_TEAR_INTERRUPTED );

		CString	strInfo;
		pFile->QueryInfo( HTTP_QUERY_SET_COOKIE, strInfo );
		pFile->QueryInfo( HTTP_QUERY_COOKIE, strInfo );
		if( strInfo.GetLength() )
			m_strCookie	=	strInfo;
		pFile->QueryInfo( HTTP_QUERY_CONTENT_LENGTH, strInfo );
		nContentLength	=	atol( strInfo );
		nContentLengthTotal = nContentLength + nContentLengthFinished;
		if( pstrResult && nContentLengthTotal > 0 )
			pstrResult->GetBuffer( nContentLengthTotal+5 );

		DWORD	dwCheckSum	=	0;
		BOOL	bHasCheckSum	=	FALSE;
		CString	strCheckSum;
		pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, strCheckSum);
		int nPlace = strCheckSum.Find( szCheckSumKeySuffix );
		if ( -1 != nPlace )
		{
			strCheckSum = strCheckSum.Mid( nPlace+strlen(szCheckSumKeySuffix) );
			nPlace = strCheckSum.Find( '\n' );
			if( nPlace > 0 )
			{
				dwCheckSum = atol( strCheckSum.Left( nPlace ) );
				bHasCheckSum	=	TRUE;
			}
		}

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

		DWORD	dwCheckSumLocal	=	0;
		TCHAR sz[1028];
		int nRead = pFile->Read(sz+4, 1023);
		while (nRead > 0)
		{
			sz[4+nRead] = '\0';
			if( NULL != pFileSave )
				pFileSave->Write( sz+4, nRead );
			if( NULL != pstrResult )
				*pstrResult	+=	(TCHAR *)(sz+4);
			nContentLengthLocal	+=	nRead;

			if( fnCallback && nContentLengthTotal > 0 )
				fnCallback( PROG_PROGRESS, DWORD(STKLIB_MAXF_PROGRESS*(nContentLengthFinished+nContentLengthLocal)/nContentLengthTotal), NULL, cookie );

			if( bHasCheckSum )
			{
				*((DWORD *)sz)	=	dwCheckSumLocal;
				dwCheckSumLocal = CRC32( sz, nRead );
			}

			nRead = pFile->Read(sz+4, 1023);
		}

		if( pstrResult && nContentLengthTotal > 0 )
			pstrResult->ReleaseBuffer();

		if( (nContentLength > 0 && nContentLengthLocal != nContentLength)
				|| (bHasCheckSum && dwCheckSum != dwCheckSumLocal) )
			ThrowTearException( ERR_TEAR_DATATRANSFER );

		if( fnCallback )
			fnCallback( PROG_PROGRESS, STKLIB_MAX_PROGRESS, NULL, cookie );
	}
	catch (CInternetException* pEx)
	{
		// catch errors from WinINet
		if (HTTP_STATUS_OK == dwRet)
			dwRet	=	HTTP_STATUS_PARTIAL;
		TCHAR szErr[1024];
		pEx->GetErrorMessage(szErr, 1024);
		m_strLastErrorMessage	=	szErr;
		pEx->Delete();
	}
	catch (CTearException* pEx)
	{
		TCHAR szErr[1024];
		pEx->GetErrorMessage(szErr, 1024);
		m_strLastErrorMessage	=	szErr;
		pEx->Delete();
	}
	catch( CException * pEx )
	{
		TCHAR szErr[1024];
		pEx->GetErrorMessage(szErr, 1024);
		m_strLastErrorMessage	=	szErr;
		pEx->Delete();
	}

	if (pFile != NULL)
	{
		pFile->Close();
		delete pFile;
	}
	if (pServer != NULL)
	{
		pServer->Close();
		delete pServer;
	}
	session.Close();

	if(nContentLength > 0 && nContentLengthLocal != nContentLength)
		return Request( lpszURL, strPostData, pFileSave, pstrResult, fnCallback, cookie );

	return dwRet;
}
예제 #18
0
파일: DlgView.cpp 프로젝트: SoyPay/DacrsUI
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;
}
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;
}
예제 #20
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;

}
예제 #21
0
BOOL CWebGrab::GetFile(LPCTSTR szURL, CString& strBuffer, 
                       LPCTSTR szAgentName /*=NULL*/, CWnd* pWnd /*=NULL*/)
{
	CString strBuffer2;

  //  TRACE1("URL is %s\n", szURL);
	m_rawHeaders ="";
	m_infoStatusCode=0;
	strBuffer.Empty();

    if (!m_pSession && !Initialise(szAgentName, pWnd))
        return FALSE;

    if (pWnd)
        m_pSession->SetStatusWnd(pWnd);

    //m_pSession->SetStatus("Downloading file...");

    DWORD dwCount = 0;
    CHttpFile* pFile = NULL;
    try
    {
        pFile = (CHttpFile*) m_pSession->OpenURL(szURL, 1,
                                                 INTERNET_FLAG_TRANSFER_BINARY 
                                                 //| INTERNET_OPEN_FLAG_USE_EXISTING_CONNECT |
                                                 | INTERNET_FLAG_DONT_CACHE
                                                 //| INTERNET_FLAG_RELOAD
                                                 );
	}
    catch (CInternetException* e)
    {
        TCHAR   szCause[255];
        e->GetErrorMessage(szCause, 255);
        m_pSession->SetStatus(szCause);
        // e->ReportError();
        e->Delete();
        delete pFile;
        pFile = NULL;
        return FALSE;
    }
    
    COleDateTime startTime = COleDateTime::GetCurrentTime();
    LPSTR pBuf = NULL;
    if (pFile)
    {
        pBuf = (LPSTR) ::GlobalAlloc(GMEM_FIXED, BUFFER_SIZE+1);
        if (!pBuf)
        {
            pFile->Close();
            delete pFile;
            return FALSE;
        }

        BYTE buffer[BUFFER_SIZE+1];
        try {
            UINT nRead = 0;
            dwCount = 0;
            do
            {
                nRead = pFile->Read(buffer, BUFFER_SIZE);
                if (nRead > 0)
                {
                    buffer[nRead] = 0;

					// JT origional code works in sample but produces Gibber here...
                    //LPTSTR ptr = strBuffer.GetBufferSetLength(dwCount + nRead + 1);
                    //memcpy(ptr+dwCount, buffer, nRead);
                    dwCount += nRead;
                    //strBuffer.ReleaseBuffer(dwCount+1);

					// My alternate
					CString str( (LPCSTR) &buffer, sizeof(buffer) );  // Convert byte array to CString
					strBuffer.Append(str);	// append CString.

                    COleDateTimeSpan elapsed = COleDateTime::GetCurrentTime() - startTime;
                    double dSecs = elapsed.GetTotalSeconds();
                    if (dSecs > 0.0)
					{
                        m_transferRate = (double)dwCount / 1024.0 / dSecs;
						//m_pSession->SetStatus("Read %d bytes (%0.1f Kb/s)", 
                        //                     dwCount, m_transferRate );
						
					}
					else
					{
                        //m_pSession->SetStatus("Read %d bytes", dwCount);
						m_transferRate = dwCount;
					}
                }
            }
            while (nRead > 0);
        }
        catch (CFileException *e)
        {
            TCHAR   szCause[255];
            e->GetErrorMessage(szCause, 255);
			m_ErrorMessage = szCause;
            m_pSession->SetStatus(szCause);
            //e->ReportError();
            e->Delete();
            delete pFile;
            ::GlobalFree(pBuf);	// mem leak fix by Niek Albers 
            return FALSE;
        }
        pFile->QueryInfoStatusCode(m_infoStatusCode);       
		pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS ,m_rawHeaders);
        pFile->Close();
	  ::GlobalFree(pBuf);	// mem leak fix by Niek Albers 
        delete pFile;
    }

    //m_pSession->SetStatus("");

    return TRUE;
}
	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;
	}
예제 #23
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;
}
예제 #24
0
int CWebBase::RequestPostPageExExEx(CString & strServer, CString & strObject, 
								  CString & strHead,CString & strPostData,
								  CString &strError,
								  int iGetType,	//表示获取文件,1表示获取验证码
								  int iIsProxy,	//是否使用代理
								  int iProxyType,//代理类型
								  CString strProxyIP,//代理IP
								  int iProxyPort,//代理端口
								  CString strProxyUser,//代理用户名
								  CString strProxyPwd//代理密码
								  )
{
	CHttpFile * pHttpFile;
	char cBuffer[1024];
	unsigned long StatusCode;
	unsigned long  iReadLen = 0;
	int            nStringLen = 0;
	CString        strTemp = "";	
	WORD            wdPort;
	BOOL result;
	int iRet = -1;
	try
	{
		//获取到参数信息
		DWORD dwFlags = GetDwflag();
		pHttpFile = NULL;
		m_strWorkBuf.Empty();
		//设置超时
		SetTimeOut(m_Session, g_iTimeOut);
		//获取连接
		iRet = GetHttpConnectionEx(strServer,strObject,strHead,strError,iIsProxy,iProxyType,strProxyIP,iProxyPort);
		if (iRet < 0)
		{
			return iRet;
		}
		//打开请求对象
		pHttpFile = m_pConnection->OpenRequest( CHttpConnection::HTTP_VERB_POST,
			(LPCTSTR)strObject,NULL, 0,
			NULL, NULL,
			dwFlags );
		if( pHttpFile == NULL )
		{
			strError = "OpenRequest失败";
			return -1;
		}
		//如果是SOCKET5代理,设置账号密码
		// 		if   (!pHttpFile->SetOption(INTERNET_OPTION_PROXY_USERNAME,strProxyUser,strProxyUser.GetLength()))   
		// 		{   
		// 			return -99;
		// 		}
		// 		if   (!pHttpFile->SetOption(INTERNET_OPTION_PROXY_PASSWORD,strProxyPwd,strProxyPwd.GetLength()))   
		// 		{   
		// 			return -99;   
		// 		}
		//发送请求到服务器		
		iRet = SendRequest(pHttpFile,strError,strHead,strPostData,1);/*发送数据*/
		if (iRet < 0)	//发送POST数据失败
		{
			//清除连接对象
			DeleteObjectExEx();
			return iRet; 
		}
		//获取状态码及头信息
		pHttpFile->QueryInfoStatusCode(StatusCode);
		pHttpFile->QueryInfo(HTTP_QUERY_LOCATION,m_strRedirectUrl); 
		pHttpFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF,m_strResponHead);
		iReadLen = (unsigned long )pHttpFile->GetLength();
		m_iStatusCode = StatusCode;
		// 是否重定向
		if ( StatusCode == HTTP_STATUS_OK ||
			StatusCode == HTTP_STATUS_MOVED ||
			StatusCode == HTTP_STATUS_REDIRECT ||
			StatusCode == HTTP_STATUS_REDIRECT_METHOD)
		{
			//获取数据
			if (iGetType == 0)			//读取文本信息
			{
				while(iReadLen >= 0)
				{
					iReadLen = pHttpFile->Read( cBuffer ,1023 );
					if (iReadLen <= 0)
					{
						break;
					}
					m_strWorkBuf += CString( cBuffer ,iReadLen);
				}
			}
			else		//读取验证码
			{
				CStdioFile out;
				out.Open(g_strDirect+g_strFileName, CFile::modeCreate | CFile::modeWrite |CFile::typeBinary);
				while(true)
				{
					iReadLen = pHttpFile->Read(cBuffer ,1);
					if ( iReadLen <= 0)
					{
						break;
					}
					out.Write(cBuffer,1); 
				}
				out.Close();
			}			
		}
		//删除HTTPFILE对象
		DeleteObjectEx(pHttpFile);	
		if(!m_strWorkBuf.IsEmpty()) //解压数据
		{
			//ConvertUtf8ToGBK( m_strWorkBuf );
			return ConvertData(m_strResponHead,strError,m_strWorkBuf);
		}
		return 0;			
	}
	catch(CInternetException * e)
	{
		strError = "抓取网页信息异常";
		DeleteObjectEx(pHttpFile);	
		DeleteObjectExEx();
		e->Delete();
		return -6;
	}
	catch(...)
	{
		strError = "抓取网页信息异常";
		DeleteObjectEx(pHttpFile);	
		DeleteObjectExEx();
		return -7;
	}
	return 0;
}
예제 #25
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;

}
예제 #26
0
파일: DLsyn.cpp 프로젝트: DLive/npadBook
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;
}
예제 #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;
}
예제 #28
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;
}
예제 #29
0
파일: tear.cpp 프로젝트: pfeilbr/repo
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;
}
예제 #30
0
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;
}