关键系统函数
CHttpConnection* CInternetSession::GetHttpConnection
CHttpFile* CHttpConnection::OpenRequest
CHttpFile::SendRequest
CInternetFile::Read
访问接口函数
int CHttpData::ExecuteRequest(LPCTSTR strMethod, LPCTSTR strUrl, CString strPostData, CString &strResponse)
{
CString strServer;
CString strObject;
DWORD dwServiceType;
INTERNET_PORT nPort;
strResponse = _T("");
CInternetSession sess;
AfxParseURL(strUrl, dwServiceType, strServer, strObject, nPort);
if(AFX_INET_SERVICE_HTTP != dwServiceType && AFX_INET_SERVICE_HTTPS != dwServiceType)
{
LoggerCio::notice(LoggerCio::LOG_URL,"*** url 非http或https 协议!");
return FAILURE;
}
try
{
m_pConnection = sess.GetHttpConnection(strServer,dwServiceType == AFX_INET_SERVICE_HTTP ? NORMAL_CONNECT : SECURE_CONNECT,nPort);
m_pFile = m_pConnection->OpenRequest(strMethod, strObject,NULL, 1, NULL, NULL,(dwServiceType == AFX_INET_SERVICE_HTTP ? NORMAL_REQUEST : SECURE_REQUEST));
m_pFile -> AddRequestHeaders( _T("Accept:application/json;"));
m_pFile -> AddRequestHeaders( _T("Content-Type:application/json;charset=utf-8;"));
m_pFile -> AddRequestHeaders( _T("Content-Type:multipart/form-data;"));
USES_CONVERSION;
char *pData = T2A(strPostData);
if (NULL == m_pFile){
LOG_FUNC_QUIT_DEBUG(LOG_SYS);
return FAILURE;
}
if(m_pFile->SendRequest(NULL, 0,pData,strlen(pData)))
{
char szChars[BUFFER_SIZE + 1] = {0};
string strRawResponse = "";
UINT nReaded = 0;
while ((nReaded = m_pFile->Read((void*)szChars, BUFFER_SIZE)) > 0)
{
szChars[nReaded] = '\0';
strRawResponse += szChars;
memset(szChars, 0, BUFFER_SIZE + 1);
}
int unicodeLen = MultiByteToWideChar(CP_UTF8, 0, strRawResponse.c_str(), -1, NULL, 0);
WCHAR *pUnicode = new WCHAR[unicodeLen + 1];
memset(pUnicode,0,(unicodeLen+1)*sizeof(wchar_t));
MultiByteToWideChar(CP_UTF8,0,strRawResponse.c_str(),-1, pUnicode,unicodeLen);
CString cs(pUnicode);
delete []pUnicode;
pUnicode = NULL;
strResponse = cs;
}
else{
DWORD dwError = GetLastError();
LoggerCio::notice(LoggerCio::LOG_URL,"*** m_pFile->SendRequest 失败,GetLastError=%d",dwError);
}
Clear();
}
catch (CInternetException* e)
{
Clear();
DWORD dwErrorCode = e->m_dwError;
e->Delete();
e = NULL;
DWORD dwError = GetLastError();
LoggerCio::notice(LoggerCio::LOG_URL,"*** CHttpData 网络异常,错误代码[CInternetException::m_dwError:%d][GetLastError:%d] ***",dwErrorCode,dwError);
if (ERROR_INTERNET_TIMEOUT == dwErrorCode)
return OUTTIME;
else
return FAILURE;
}
return SUCCESS;
}