本文介绍了断开网络连接后,为什么可以使用CHttpConnection和CHttpFile下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
BOOL Download(CString& m_strDownLoadURL,CString& m_strDownLoadDesFileName)
{
ASSERT(m_strDownLoadURL != "");
ASSERT(m_strDownLoadDesFileName != "");
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(m_strDownLoadURL, 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(m_strDownLoadDesFileName, 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(...)
{
// do something
}
推荐答案
这篇关于断开网络连接后,为什么可以使用CHttpConnection和CHttpFile下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!