通过代理访问web

来源:互联网 发布:淘宝莆田鞋店推荐 编辑:程序博客网 时间:2024/05/12 00:53

下面这段是获取本地代理服务器设置的。其中,用到了下面三个成员变量:

 CString m_PassWord;
 CString m_UserName;
 LPINTERNET_PROXY_INFO m_ProxyInfo;

void CGetWebFile::GetProxy()
{
 DWORD dwSize;
 InternetQueryOption(NULL,INTERNET_OPTION_PROXY,NULL,&dwSize);
 if(dwSize > 0)
 {
  BYTE *lpszData = new BYTE[dwSize];
  InternetQueryOption(NULL,   INTERNET_OPTION_PROXY,lpszData,&dwSize);
  m_ProxyInfo = (LPINTERNET_PROXY_INFO)lpszData;
  
  InternetQueryOption(NULL, INTERNET_OPTION_PROXY_USERNAME, NULL, &dwSize);
  if(dwSize > 0)
  {
   lpszData = new BYTE[dwSize];
   InternetQueryOption(NULL, INTERNET_OPTION_PROXY_USERNAME, lpszData, &dwSize);
   m_UserName = lpszData;
   delete []lpszData;
  }
  
  InternetQueryOption(NULL, INTERNET_OPTION_PROXY_PASSWORD, NULL, &dwSize);
  if(dwSize > 0)
  {
   lpszData = new BYTE[dwSize];
   InternetQueryOption(NULL, INTERNET_OPTION_PROXY_PASSWORD, lpszData, &dwSize);
   m_PassWord = lpszData;
   delete []lpszData;
  }
 }
}

下面这段代码,是利用代理服务器下载文件的:

BOOL CGetWebFile::GetWebFile(CString theUrl, CString Filename,
          PX_TYPE nUseProxy/* = PX_AUTO*/,
          LPCTSTR proxyServer/* = NULL*/, WORD proxyPort/* = 8080*/,
          LPCTSTR proxyUser/* = NULL*/, LPCTSTR proxyPassword/* = NULL*/)
{
 LPINTERNET_PROXY_INFO pProxyInfo = NULL;
 CString strUserName;
 CString strUserPassword;

// DWORD dwSize;
// char *lpszData;
 INTERNET_PROXY_INFO proxyInfo;
 CString proxyString;
 CInternetSession session;
 CInternetFile* file = NULL;
 try
 {
  // Try to connect with the URL
  pProxyInfo = m_ProxyInfo;
  if(pProxyInfo)
  {
   if(!session.SetOption(INTERNET_OPTION_PROXY, (LPVOID)pProxyInfo, sizeof(INTERNET_PROXY_INFO)))
   {
    return FALSE;
   }
  }
  file = (CInternetFile*)session.OpenURL(theUrl);
  if(pProxyInfo)
  {
   if((!strUserName.IsEmpty()) && (!strUserPassword.IsEmpty()))
   {
    if( (!file->SetOption(INTERNET_OPTION_PROXY_USERNAME, (DWORD)strUserName.GetBuffer(strUserName.GetLength()), strUserName.GetLength() + 1)) ||
     (!file->SetOption(INTERNET_OPTION_PROXY_PASSWORD, (DWORD)strUserPassword.GetBuffer(strUserPassword.GetLength()), strUserPassword.GetLength() + 1)))
    {
     file->Close();
     delete file;
     return FALSE;
    }
   }
  }
 }
 catch (CInternetException* m_pException)
 {
  // if some error occurs, set the file with NULL
  file = NULL;
  m_pException->Delete();
  return FALSE;
 }
 
 BOOL bRet = FALSE;
 // use dataStore to save the file content
 CStdioFile dataStore;
 if(dataStore.Open(Filename, CFile::modeCreate | CFile::modeWrite | CFile::shareDenyWrite | CFile::typeBinary))
 {
  if (file)
  {
   #define BUFFER_SIZE 2048
   UINT somelen = 0;
   BYTE somecode[BUFFER_SIZE];
   while((somelen = file->Read(somecode, BUFFER_SIZE)) > 0)
   {
    dataStore.Write(somecode, somelen);
   }
   bRet = TRUE;
  }
  dataStore.Close();
 }
 if(file)
 {
  file->Close();
  delete file;
 }
 return bRet;
}

原创粉丝点击