【问题分析】
在new CInternetSession时出错的代码:
m_pSession = new CInternetSession;
if (m_pSession)
{
m_pSession->SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 300);
m_pHttpConn = m_pSession->GetHttpConnection(m_strServer, m_nPort);
}
上面的代码其实一点毛病都没有,跟踪发现出错在它的构造函数的 AfxGetAppName() 在获取AppName失败了!
CInternetSession::CInternetSession(LPCTSTR pstrAgent /* = NULL */,
DWORD_PTR dwContext /* = 1 */,
DWORD dwAccessType /* = PRE_CONFIG_INTERNET_ACCESS */,
LPCTSTR pstrProxyName /* = NULL */,
LPCTSTR pstrProxyBypass /* = NULL */,
DWORD dwFlags /* = 0 */)
{
ASSERT((dwFlags & INTERNET_FLAG_ASYNC) == 0);
m_bCallbackEnabled = FALSE;
m_pOldCallback = NULL;
m_dwContext = dwContext;
if (pstrAgent == NULL)
pstrAgent = AfxGetAppName();
m_hSession = InternetOpen(pstrAgent, dwAccessType,
pstrProxyName, pstrProxyBypass, dwFlags);
if (m_hSession == NULL)
AfxThrowInternetException(m_dwContext);
else
_afxSessionMap.SetAt(m_hSession, this);
}
【解决方案】
在执行CInternetSession构造函数之前(也就是在调用CInternetSession之前),添加下面三行代码:
CWinApp app(L"YourAppName.dll");
app.InitApplication();
AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0);