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;  //成功
}  

猜你喜欢

转载自blog.csdn.net/qiangzi4646/article/details/80667090