1. 程式人生 > >MFC 通過 http (post/get) 訪問WEB(介面)伺服器,並取得伺服器返回資料

MFC 通過 http (post/get) 訪問WEB(介面)伺服器,並取得伺服器返回資料

關鍵系統函式

CHttpConnection* CInternetSession::GetHttpConnection
CHttpFile* CHttpConnection::OpenRequest
CHttpFile::SendRequest
CInternetFile::Read

訪問介面函式

//strMethod:型別包含 POST/GET ,strUrl訪問的網址,strPostData:型別為POST時提交給伺服器的資料,strResponse:伺服器返回資料
int CHttpData::ExecuteRequest(LPCTSTR strMethod, LPCTSTR strUrl, CString/*LPCTSTR*/
strPostData, CString &strResponse) { CString strServer; CString strObject; DWORD dwServiceType; INTERNET_PORT nPort; strResponse = _T(""); CInternetSession sess;//Create session AfxParseURL(strUrl, dwServiceType, strServer, strObject, nPort); //解析url //判斷協議型別是否為http或https
if(AFX_INET_SERVICE_HTTP != dwServiceType && AFX_INET_SERVICE_HTTPS != dwServiceType) { LoggerCio::notice(LoggerCio::LOG_URL,"*** url 非http或https 協議!");//log輸出 return FAILURE; } try { //CHttpConnection *m_pConnection;//定義在標頭檔案 //獲取 CHttpConnection*
m_pConnection = sess.GetHttpConnection(strServer,dwServiceType == AFX_INET_SERVICE_HTTP ? NORMAL_CONNECT : SECURE_CONNECT,nPort); //獲取 CHttpFile* 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); } //將多字元轉寬位元組存為 CString 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) { //捕獲CInternetException異常 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; //成功 }