1、定義連接對象 (對象定義在.h文件中)
//定義Http請求傳輸對象 CHttpConnection* m_pConnection; CHttpFile* m_pFile; CInternetSession sess;//Create session
2、實現:
參數:
LPCTSTR strMethod:請求的方式是Post還是Get;
LPCTSTR strUrl:請求的web地址;
CString strPostData:上傳的數據;
CString &strResponse:獲取返回值;
CString CWebJNDataOcxCtrl::ExecuteRequest( LPCTSTR strMethod, LPCTSTR strUrl, CString strPostData, CString &strResponse ) { CString strServer; CString strObject; DWORD dwServiceType; INTERNET_PORT nPort; strResponse = _T(""); CString strState = _T(""); 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 _T("不是http協議"); } try { //CHttpConnection *m_pConnection;//定義在頭文件 //獲取 CHttpConnection* m_pConnection = sess.GetHttpConnection(strServer ,nPort); //獲取 CHttpFile* m_pFile = m_pConnection->OpenRequest(strMethod, strObject,NULL, 1, NULL, NULL,INTERNET_FLAG_EXISTING_CONNECT); 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 _T("Open Error!"); } //發送請求 if(m_pFile->SendRequest(NULL, 0,pData,strlen(pData))) { char szChars[BUFFER_SIZE + 1] = {0}; string strRawResponse = ""; UINT nReaded = 0; CString str = _T(""); while ((nReaded = m_pFile->Read((void*)szChars, BUFFER_SIZE)) > 0) {//接收返回 szChars[nReaded] = '\0'; strRawResponse += szChars; str = strRawResponse.c_str(); strResponse = CallBackState(str, strPostData); //AfxMessageBox(strResponse, MB_ICONINFORMATION); strState = strResponse; 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; return strState; //成功 } else{//請求失敗打印錯誤碼 DWORD dwError = GetLastError(); //LoggerCio::notice(LoggerCio::LOG_URL,"*** m_pFile->SendRequest 失敗,GetLastError=%d",dwError); return _T("請求失敗"); //錯誤 } } catch (CInternetException* e) { //捕獲CInternetException異常 DWORD dwErrorCode = e->m_dwError; e->Delete(); e = NULL; strState = _T("4"); DWORD dwError = GetLastError(); return strState; } }