#include "stdafx.h"
#include "windows.h"
//adostream中保存了,網(wǎng)頁轉(zhuǎn)為mht后的內(nèi)容
#import "c:\\program files\\common files\\system\\ado\\msado15.dll" no_namespace raw_interfaces_only
//將網(wǎng)頁轉(zhuǎn)為mht的主要組件
#import "C:\\Windows\\system32\\cdosys.dll" no_namespace raw_interfaces_only
//將unicode轉(zhuǎn)為utf-8[否則生成的文件,中文亂碼]
char* ToUTF8( WCHAR* str );
//主要函數(shù)
int SaveWholePage(wchar_t* szPageURL,wchar_t* szFileName)
{
CoInitialize(NULL);
BSTR bstr=szPageURL;
wchar_t* szUserName=L"domain\\username";//domain\\username
BSTR bstrUserName=szUserName;
wchar_t* szPass=L"domain\\username";//domain\\username
BSTR bstrPass=szPass;
IMessage *pMsg=NULL;
IConfiguration* pConfig = NULL;
HRESULT hr=CoCreateInstance( __uuidof(Message), NULL, CLSCTX_INPROC_SERVER, __uuidof(IMessage), (void**)&pMsg);
hr=CoCreateInstance(__uuidof(Configuration),NULL,CLSCTX_INPROC_SERVER,__uuidof(IConfiguration),(void**)&pConfig);
pMsg->put_Configuration (pConfig);
//將網(wǎng)頁轉(zhuǎn)為mht
hr = pMsg->CreateMHTMLBody(bstr,cdoSuppressNone,bstrUserName,bstrPass );//cdoSuppressAll
if (FAILED(hr))
{
pMsg->CreateMHTMLBody(bstr,cdoSuppressNone,bstrUserName,bstrPass );
}
//獲取到adostream中
_Stream* pStm = NULL;
pMsg->GetStream(&pStm);
pStm->put_Position(0);
pStm->put_Charset(L"UTF-8");//設(shè)置編碼
long nsize;
pStm->get_Size(&nsize);
BSTR strruss;
pStm->ReadText(nsize,&strruss);//讀取
//當我用pstm->savetofile函數(shù)時,會有不知名的錯誤,導致有時無法生成,所以選擇了自己創(chuàng)建文件
HANDLE hFile = CreateFileW(szFileName,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
wprintf(L"open file error\n");
return 0;
}
DWORD csize;
char* pstr = ToUTF8(strruss);//這里調(diào)用了轉(zhuǎn)碼[防止中文亂碼]
bool bRet = WriteFile(hFile,pstr,strlen(pstr),&csize,NULL);
delete pstr;
if (bRet)
{
wprintf(L"write file succeed\n");
}
CloseHandle(hFile);
pMsg->Release();
pStm->Release();
CoUninitialize();
return 1;
}
//Unicode to UTF-8
char* ToUTF8(WCHAR* str)
{
char* pElementText;
int iTextLen;
// wide char to multi char
iTextLen = WideCharToMultiByte( CP_UTF8,
0,
str,
-1,
NULL,
0,
NULL,
NULL);
pElementText = new char[iTextLen + 1];
memset( ( void* )pElementText, 0, sizeof( char ) * ( iTextLen + 1 ) );
WideCharToMultiByte( CP_UTF8,
0,
str,
-1,
pElementText,
iTextLen,
NULL,
NULL);
return pElementText;
}
int _tmain(int argc, _TCHAR* argv[])
{
SaveWholePage(L"http://blog.klniu.com/post/qstring-wchar_t-tchar-and-other-types-of-conversion-characters-or-strings/",L"E:\\test.mht");
return 0;
}