HTTP上传和下载文件

在PC机和WCE上均能使用,使用的是MFC的库,已通过测试,记得加头文件#include<afxinet.h>

下载文件:

ExpandedBlockStart.gif 代码
bool  Download(  const   CString  &   strFileURLInServer,   //  待下载文件的URL 
               const   CString   &   strFileLocalFullPath)  //  存放到本地的路径 
{
    ASSERT(strFileURLInServer 
!=   "" );
    ASSERT(strFileLocalFullPath 
!=   "" );
    CInternetSession session;
    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);
        
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);
        }
    }
    
catch (CInternetException *  e) 
    { 
        TCHAR tszErrString[
256 ]; 
        e
-> GetErrorMessage(tszErrString,  sizeof (tszErrString)); 
        TRACE(_T(
" Download XSL error! URL: %s,Error: %s " ), strFileURLInServer, tszErrString); 
        e
-> Delete(); 
    } 
    
catch (...)
    {
    }

    
if (pszBuffer  !=  NULL) 
    { 
        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   true ;
}

测试代码:

 

1  CString URLInServer;
2      CString    LocalFullPath;
3      URLInServer  =   " http://www.163.com/photo " ;
4      LocalFullPath  =   " \\test.html " ;
5      Download(URLInServer,LocalFullPath);

 修改后,代码

 

ExpandedBlockStart.gif 代码
  1  bool  CHttpClient::Download(  const    string   &   strFileURLInServer,   //  待下载文件的URL 
  2                 const    string    &   strFileLocalFullPath)  //  存放到本地的路径 
  3  {
  4      ASSERT(strFileURLInServer  !=   "" );
  5      ASSERT(strFileLocalFullPath  !=   "" );
  6      CInternetSession session;
  7      CHttpConnection *  pHttpConnection  =  NULL;
  8      CHttpFile *  pHttpFile  =  NULL;
  9      CString strServer, strObject;
 10      INTERNET_PORT wPort;
 11 
 12      DWORD dwType;
 13       const   int  nTimeOut  =   2000 ;
 14      session.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, nTimeOut);  // 重试之间的等待延时
 15      session.SetOption(INTERNET_OPTION_CONNECT_RETRIES,  1 );    // 重试次数
 16       char *  pszBuffer  =  NULL;  
 17 
 18       try
 19      {
 20          CString tmp;
 21          tmp.Format( " %s " ,strFileURLInServer.c_str());
 22          AfxParseURL(tmp, dwType, strServer, strObject, wPort);
 23          pHttpConnection  =  session.GetHttpConnection(strServer, wPort);
 24          pHttpFile  =  pHttpConnection -> OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject);
 25           if (pHttpFile -> SendRequest()  ==  FALSE)
 26               return   false ;
 27          DWORD dwStateCode;
 28 
 29          pHttpFile -> QueryInfoStatusCode(dwStateCode);
 30           if (dwStateCode  ==  HTTP_STATUS_OK)
 31          {
 32               // CString LocalFullPath;
 33              tmp.Format( " %s " ,strFileLocalFullPath.c_str());
 34              HANDLE hFile  =  CreateFile(tmp, GENERIC_WRITE,
 35                  FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
 36                  NULL);   // 创建本地文件
 37               if (hFile  ==  INVALID_HANDLE_VALUE)
 38              {
 39                  pHttpFile -> Close();
 40                  pHttpConnection -> Close();
 41                  session.Close();
 42                   return   false ;
 43              }
 44 
 45               char  szInfoBuffer[ 1000 ];   // 返回消息
 46              DWORD dwFileSize  =   0 ;    // 文件长度
 47              DWORD dwInfoBufferSize  =   sizeof (szInfoBuffer);
 48              BOOL bResult  =  FALSE;
 49              bResult  =  pHttpFile -> QueryInfo(HTTP_QUERY_CONTENT_LENGTH,
 50                  ( void * )szInfoBuffer, & dwInfoBufferSize,NULL);
 51 
 52              dwFileSize  =  atoi(szInfoBuffer);
 53               const   int  BUFFER_LENGTH  =   1024   *   10 ;
 54              pszBuffer  =   new   char [BUFFER_LENGTH];   // 读取文件的缓冲
 55              DWORD dwWrite, dwTotalWrite;
 56              dwWrite  =  dwTotalWrite  =   0 ;
 57              UINT nRead  =  pHttpFile -> Read(pszBuffer, BUFFER_LENGTH);  // 读取服务器上数据
 58 
 59               while (nRead  >   0 )
 60              {
 61                  WriteFile(hFile, pszBuffer, nRead,  & dwWrite, NULL);   // 写到本地文件
 62                  dwTotalWrite  +=  dwWrite;
 63                  nRead  =  pHttpFile -> Read(pszBuffer, BUFFER_LENGTH);
 64              }
 65 
 66              delete[]pszBuffer;
 67              pszBuffer  =  NULL;
 68              CloseHandle(hFile);
 69          }
 70           else
 71          {
 72              delete[]pszBuffer;
 73              pszBuffer  =  NULL;
 74               if (pHttpFile  !=  NULL)
 75              {
 76                  pHttpFile -> Close();
 77                  delete pHttpFile;
 78                  pHttpFile  =  NULL;
 79              }
 80               if (pHttpConnection  !=  NULL)
 81              {
 82                  pHttpConnection -> Close();
 83                  delete pHttpConnection;
 84                  pHttpConnection  =  NULL;
 85              }
 86              session.Close();
 87               return   false ;
 88          }
 89      }
 90       catch (...)
 91      {
 92          delete[]pszBuffer;
 93          pszBuffer  =  NULL;
 94           if (pHttpFile  !=  NULL)
 95          {
 96              pHttpFile -> Close();
 97              delete pHttpFile;
 98              pHttpFile  =  NULL;
 99          }
100           if (pHttpConnection  !=  NULL)
101          {
102              pHttpConnection -> Close();
103              delete pHttpConnection;
104              pHttpConnection  =  NULL;
105          }
106          session.Close();
107           return   false ;
108      }
109 
110       if (pHttpFile  !=  NULL)
111      {
112          pHttpFile -> Close();
113          delete pHttpFile;
114          pHttpFile  =  NULL;
115      }
116       if (pHttpConnection  !=  NULL)
117      {
118          pHttpConnection -> Close();
119          delete pHttpConnection;
120          pHttpConnection  =  NULL;
121      }
122      session.Close();
123       return   true ;
124  }
125 

 

 

上传文件:

 

ExpandedBlockStart.gif 代码
UploadFile(LPCTSTR strURL, //负责接收上传操作的页面的URL
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(CFileException& fe)
 {
  CString str;
  str.Format("FileException occur!\r\n%d", fe.m_lOsError);
  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;
}

 

 

转载于:https://www.cnblogs.com/fairycao/archive/2009/12/09/1620394.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值