zoukankan      html  css  js  c++  java
  • c++ Get方式获取页面源码(unicode编码)。

    
    
    CString CHttpClient::doGet(CString href) 
    { 
        std::string httpsource;
        CInternetSession session1(NULL,0); 
        CHttpFile* pHTTPFile=NULL; 
    
        try{ 
            pHTTPFile=(CHttpFile*)session1.OpenURL(href); 
        }catch(CInternetException* m_pException){ 
            //捕捉错误,否则在网络断开时连接导致内存问题
            pHTTPFile=NULL; 
            m_pException->m_dwError;
            m_pException->Delete();
            session1.Close(); 
            return _T("");
        } 
        if(pHTTPFile) 
        {
            char sRecived[2048]={0};//初始化,避免内存问题
    
            pHTTPFile->ReadString((LPTSTR)sRecived,1024);//避免使用CString导致乱码,unicode编码时一个字符用两个字节来编码,第二个参数使用字符数
            do
            {
                httpsource+=sRecived;
                memset(sRecived,0,2048);
                //httpsource.append(sRecived);
            } while (pHTTPFile->ReadString((LPTSTR)sRecived,1024)>0);
            pHTTPFile->Close(); 
            delete pHTTPFile; 
            delete[] sRecived;
        } 
        session1.Close();
        wstring result=UTF8ToUnicode(httpsource);//转码
        return result.c_str();
    } 
    
    std::string CHttpClient::UnicodeToUTF8( const std::wstring& str )
    {
     char*     pElementText;
     int    iTextLen;
     // wide char to multi char
     iTextLen = WideCharToMultiByte( CP_UTF8,
             0,
             str.c_str(),
             -1,
             NULL,
             0,
             NULL,
             NULL );
     pElementText = new char[iTextLen + 1];
     memset( ( void* )pElementText, 0, sizeof( char ) * ( iTextLen + 1 ) );
     ::WideCharToMultiByte( CP_UTF8,
             0,
             str.c_str(),
             -1,
             pElementText,
             iTextLen,
             NULL,
             NULL );
     std::string strText;
     strText = pElementText;
     delete[] pElementText;
     return strText;
    }
    
    wstring CHttpClient::UTF8ToUnicode( const string& str )
    {
    	int  len = 0;
    	len = str.length();
    	int  unicodeLen = ::MultiByteToWideChar( CP_UTF8,
    		0,
    		str.c_str(),
    		-1,
    		NULL,
    		0 ); 
    	wchar_t *  pUnicode; 
    	pUnicode = new  wchar_t[unicodeLen+1]; 
    	memset(pUnicode,0,(unicodeLen+1)*sizeof(wchar_t)); 
    	::MultiByteToWideChar( CP_UTF8,
    		0,
    		str.c_str(),
    		-1,
    		(LPWSTR)pUnicode,
    		unicodeLen ); 
    	wstring  rt; 
    	rt = ( wchar_t* )pUnicode;
    	delete  pUnicode;
    	return  rt; 
    }
    
    
    

      

     
  • 相关阅读:
    2019.9.6文艺理论笔记
    2019.9.5作业整理
    2019下高级英语笔记
    2019下实用口才课笔记
    【学英语~磨耳朵】2013年以来看过的所有美剧&电影&纪录片等等
    python温度转换代码
    python蟒蛇绘制的代码以及目前还不知道怎么用的RGB颜色对照表
    看TED演讲——Why you will fail to have a great career
    结构与算法(5)-----队列
    结构与算法(4)-----栈
  • 原文地址:https://www.cnblogs.com/cthulhu/p/3411972.html
Copyright © 2011-2022 走看看