小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

URLDownloadToFile

 悟靜 2012-11-11

(獲取ie之中的下載文件)c#調(diào)用URLDownloadToFile

c#調(diào)用URLDownloadToFile
  1. using System.Runtime.InteropServices;
  2.    [DllImport("urlmon.dll", CharSet = CharSet.Auto, SetLastError = true)]
  3.        public static extern Int32 URLDownloadToFile(
  4.        [MarshalAs(UnmanagedType.IUnknown)] object pCaller,
  5.        [MarshalAs(UnmanagedType.LPWStr)] string szURL,
  6.        [MarshalAs(UnmanagedType.LPWStr)] string szFileName,
  7.        Int32 dwReserved,
  8.        IntPtr lpfnCB);
  9.          //下載
  10.          int iresult = URLDownloadToFile(null, sUrlYzm, sFileYzmGif, 0, IntPtr.Zero);
  11.          if (iresult != 0)
  12.             return;

URLDownloadToFile

在服務(wù)中、一般程序中利用 Inet 相關(guān)函數(shù)下載數(shù)據(jù)[原創(chuàng)]
雖然可以使用 URLDownloadFileToXXX() 這個 API,但是,它在使用了代理的時候會遇到麻煩。
這點(diǎn),Windows 自動更新發(fā)生過這樣的問題:如果使用了 IE 代理,如果下載代碼位于系統(tǒng)賬號
下,代理設(shè)置可能會失效。當(dāng)然,也可以為系統(tǒng)賬號手動設(shè)置代理(其實(shí)就是 IE 的代理的設(shè)置
方法),不過,程序會受到很多的限制。

所以,可以考慮使用下屬兩個函數(shù)進(jìn)行使用 - 服務(wù)程序亦可。
// Download a file from the URL.
bool CHttpDownload::UrlDownloadToFile(TCHAR *ptszURL, TCHAR *ptszFilePath)
{
      
        HINTERNET                                hNet;
        HINTERNET                                hFile;
        std::string                                sProxyServer;

        DWORD                                        dwStatusCode;
        TCHAR                                        dwStatusCode1[32] = {0};
        DWORD                                        dwSize1 = sizeof(dwStatusCode1),        dwSize = sizeof(DWORD);
      
        int                                                nfilesize;                        // file size, 2GB limited. ;)

        m_sUrl = ptszURL;
        //OutputDebugString("\nCHttpDownload::UrlDownloadToFile() ++");

        //
        if(m_ConnectionType == UseProxy)
        {
                //OutputDebugString("\n ==> Useproxy");
                hNet = InternetOpen(tszAgent, INTERNET_OPEN_TYPE_PROXY, m_sProxy.c_str(), NULL, 0);
        }
        else if(m_ConnectionType == DirectToInternet)      
        {
                //OutputDebugString("\n ==> DirectToInternet");
                hNet = InternetOpen(tszAgent, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
        }
        else if(m_ConnectionType == UsePreConfig)      
        {
                //OutputDebugString("\n ==> UsePreConfig");
                hNet = InternetOpen(tszAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
        }


        if(hNet == NULL)
        {
                //OutputDebugString("\nCHttpDownload::UrlDownloadToFile() --.1");
                return false;
        }

        hFile = InternetOpenUrl(hNet, m_sUrl.c_str(), NULL, 0, 0, 0);
        if(hFile == NULL)
        {
                InternetCloseHandle(hNet) ;
                //OutputDebugString(m_sUrl.c_str());
                //OutputDebugString(ptszURL);
                //OutputDebugString("\nCHttpDownload::UrlDownloadToFile() --.2");

                return false;
        }
      
        BOOL bRet = HttpQueryInfo(hFile, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER,&dwStatusCode,&dwSize,NULL);
        if(200 != dwStatusCode)                // if URI is not exist, give up.
        {
                InternetCloseHandle(hNet) ;
                InternetCloseHandle(hFile) ;
                //OutputDebugString("\nCHttpDownload::UrlDownloadToFile() --.3");

                return false;
        }
        if(HttpQueryInfo(hFile,HTTP_QUERY_CONTENT_LENGTH, &dwStatusCode1,&dwSize1,NULL))
        {
                nfilesize = atoi(dwStatusCode1);                // file size.
        }
      
        HANDLE hDownFile = CreateFile(ptszFilePath,
                                                                GENERIC_READ|GENERIC_WRITE,
                                                                FILE_SHARE_READ,
                                                                NULL,
                                                                CREATE_ALWAYS,
                                                                FILE_ATTRIBUTE_NORMAL,
                                                                NULL);

        if(INVALID_HANDLE_VALUE == hDownFile)
        {
                InternetCloseHandle(hNet) ;
                InternetCloseHandle(hFile) ;
                //OutputDebugString("\nCHttpDownload::UrlDownloadToFile() --.4");

                return false;
        }

        // O.K. save file
        DWORD dwWrite, dwBytesRead = 0;
        char  bufFile[MAX_BUFFER_SIZE] = {0};
        DWORD dwSurplus = nfilesize % sizeof(bufFile);      

        while(true)
        {
                // Read File Data From Net.
                BOOL bRead = InternetReadFile(hFile, bufFile, sizeof(bufFile), &dwBytesRead);
                if(dwBytesRead == 0)                // End of file.
                        break;

                // Write file data.
                WriteFile(hDownFile, bufFile, dwBytesRead, &dwWrite,NULL);
        }

        InternetCloseHandle(hFile) ;
        InternetCloseHandle(hNet) ;
        CloseHandle(hDownFile) ;

        //OutputDebugString("\nCHttpDownload::UrlDownloadToFile() --.");
        return true;
}

// Download URL contents to memory buffer.
// if pBuf == NULL, *pdwBufSize will contain the real size of remote size;
// *pdwBufSize alwayls contains the size of remote size.
bool CHttpDownload::UrlDownloadToBuffer(TCHAR *ptszURL, LPVOID pBuf, DWORD *pdwBufSize)
{
      
        HINTERNET                                hNet;
        HINTERNET                                hFile;
        std::string                                sProxyServer;
      
        DWORD                                        dwStatusCode;
        TCHAR                                        dwStatusCode1[32] = {0};
        DWORD                                        dwSize1 = sizeof(dwStatusCode1),        dwSize = sizeof(DWORD);
      
        int                                                nfilesize;                        // file size, 2GB limited. ;)
      
        m_sUrl                = ptszURL;
      
        //OutputDebugString("\nCHttpDownload::UrlDownloadToFile() ++");
      
        //
        if(m_ConnectionType == UseProxy)
                hNet = InternetOpen(tszAgent, INTERNET_OPEN_TYPE_PROXY, m_sProxy.c_str(), NULL, 0);
        else if(m_ConnectionType == DirectToInternet)      
                hNet = InternetOpen(tszAgent, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
        else if(m_ConnectionType == UsePreConfig)      
                hNet = InternetOpen(tszAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
      
      
        if(hNet == NULL)
        {
                //OutputDebugString("\nCHttpDownload::UrlDownloadToFile() --.1");
                return false;
        }
      
        hFile = InternetOpenUrl(hNet, m_sUrl.c_str(), NULL, 0, 0, 0);
        if(hFile == NULL)
        {
                InternetCloseHandle(hNet) ;
                //OutputDebugString("\nCHttpDownload::UrlDownloadToFile() --.2");
              
                return false;
        }
      
        BOOL bRet = HttpQueryInfo(hFile, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER,&dwStatusCode,&dwSize,NULL);
        if(200 != dwStatusCode)                // if URI is not exist, give up.
        {
                InternetCloseHandle(hNet) ;
                InternetCloseHandle(hFile) ;
                //OutputDebugString("\nCHttpDownload::UrlDownloadToFile() --.3");
              
                return false;
        }
        if(HttpQueryInfo(hFile, HTTP_QUERY_CONTENT_LENGTH, &dwStatusCode1, &dwSize1, NULL))
        {
                nfilesize = atoi(dwStatusCode1);                // file size.
              
        }
      
        char                                szBuffer[MAX_BUFFER_SIZE+1] = {0};
        if(pBuf != NULL)        // We only copy the 1st MAX_BUFFER_SIZE data to user buffer!!!
        {
                unsigned long nSize = 0;               
                BOOL bRet = InternetReadFile(hFile, szBuffer, MAX_BUFFER_SIZE, &nSize);
                szBuffer[nSize] = '\0';
                // dump buffer.
                DWORD        dwtSize = (*pdwBufSize > nSize)? nSize: *pdwBufSize;
                memcpy(pBuf, szBuffer, dwtSize);
        }      
        *pdwBufSize = nfilesize;
        InternetCloseHandle(hFile) ;
        InternetCloseHandle(hNet) ;
        return true;      
}

注意,
用HTTP_QUERY_CONTENT_LENGTH只是返回本次請求得到數(shù)據(jù)的長度,如果要得到整個文件的大小,
用HTTP_QUERY_CONTENT_RANGE,然后解析得到的字符串,就可以了。
HTTP_STATUS_OK = 200

***************************************************************************************

用CHttpFile實(shí)現(xiàn)簡單的GET/POST數(shù)據(jù)

一、GET 數(shù)據(jù),下載網(wǎng)頁,文件等,用于可下載的文件,不能用于服務(wù)端運(yùn)行的程序,比如.aspx文件等,否則會返回500錯誤。

    CString strSentence, strWriteName="1.htm";
    CString strFileName="http://localhost/InDesign/" + strWriteName;
    CInternetSession sess;
    CHttpFile* fileGet;
    try
    {
        fileGet=(CHttpFile*)sess.OpenURL(strFileName);
    }
    catch(CException* e)
    {
        fileGet = 0;
        throw;
    }   

    if(fileGet)
    {
        DWORD dwStatus;
        DWORD dwBuffLen = sizeof(dwStatus);
        BOOL bSuccess = fileGet->QueryInfo(HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, &dwStatus, &dwBuffLen);

        if( bSuccess && dwStatus>= 200 && dwStatus<300 )
        {
            CStdioFile fileWrite;
            if(fileWrite.Open(strWriteName, CFile::modeWrite|CFile::modeCreate))
            {
                while(fileGet->ReadString(strSentence))
                {
                    fileWrite.WriteString(strSentence+"\n");
                }
                fileWrite.Close();
                AfxMessageBox("下載完畢");
            }
            else
            {
                AfxMessageBox("本地文件"+strWriteName+"打開出錯.");
            }
        }
        else
        {
            strSentence.Format("打開網(wǎng)頁文件出錯,錯誤碼:%d", dwStatus);
            AfxMessageBox(strSentence);
        }
        fileGet->Close();
        delete fileGet;
    }
    else
        AfxMessageBox("不能找到網(wǎng)頁文件!");

    sess.Close();

二、POST 數(shù)據(jù),比如用于提交注冊信息等
CString strHttpName="http://localhost/TestReg/RegForm.aspx"; // 需要提交數(shù)據(jù)的頁面
    CString strFormData = "username=abc&password=123";    // 需要提交的數(shù)據(jù)

    CInternetSession sess;
    CHttpFile* fileGet;
    CString strHeaders = _T("Content-Type: application/x-www-form-urlencoded"); // 請求頭

    try
    {
        fileGet=(CHttpFile*)sess.OpenURL(strHttpName);//打開文件
    }
    catch(CException* e)
    {
        fileGet = 0;
        throw;
    }

    CString strSentence, strGetSentence = "";
    if(fileGet)
    {
        DWORD dwStatus;
        DWORD dwBuffLen = sizeof(dwStatus);
        BOOL bSuccess = fileGet->QueryInfo(HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, &dwStatus, &dwBuffLen);
        if( bSuccess && dwStatus>= 200 &&dwStatus<300 )
        {
            BOOL result = fileGet->SendRequest(strHeaders, (LPVOID)(LPCTSTR)strFormData, strFormData.GetLength());
            while(fileGet->ReadString(strSentence))    // 讀取提交數(shù)據(jù)后的返回結(jié)果
            {
                strGetSentence = strGetSentence + strSentence + char(13) + char(10);
            }
            AfxMessageBox(strGetSentence); // 顯示返回網(wǎng)頁內(nèi)容
        }
        else
        {
            strSentence.Format("POST出錯,錯誤碼:%d", dwStatus);
            AfxMessageBox(strSentence);
        }
       
        fileGet->Close();
        delete fileGet;
    }
    else
        AfxMessageBox("不能找到網(wǎng)頁文件!");
    sess.Close();

當(dāng)然也可以用直接用Api函數(shù)URLDownloadToFile()來下載一個文件.

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多