MFC 通过 http (post/get) 访问WEB(接口)服务器,并取得服务器返回数据

论坛 期权论坛 脚本     
匿名网站用户   2020-12-21 09:08   14   0

关键系统函数

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

调用示例

  //我的post数据一般格式,Json库是 JsonCpp
  //格式化json串
  Json::Value root;
  root["id"] = Json::Value(theApp.g_nID);
  root["verify"] = Json::Value(CSTR_2_STR(theApp.g_strVerify));
  root["check_time"] = Json::Value(theApp.g_nCheckTime);
  root["oem"] = Json::Value("");
  strPostData= STR_2_CSTR(root.toStyledString());
  
  ExecuteRequest(_T("POST"), strUrl/*请求接口*/, strPostData/*接口所需的参数,这个需要和接口提供方协商,一般是json字串*/, strResponse/*服务器返回的字串*/);

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:1136255
帖子:227251
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP