mfc: http请求get/post

效果:
在IDC_EDIT_HTTP_INPUT 输入http请求
在IDC_EDIT_HTTP_OUTPUT 反馈返回数据json格式的
mfc: http请求get/post_第1张图片


void CTG_HelperDlg::OnBnClickedButtonSubmit()
{
	CString str;
GetDlgItem(IDC_EDIT_HTTP_INPUT)->GetWindowText(str);
AppendToOutput(str);
 
CString rsp = L"";
CString post_data = L"";
ExecuteRequest(
			  L"GET",
			  str,
			  post_data,
			  rsp
			  );
TRACE("rsp:%s",rsp);
}

void CTG_HelperDlg::AppendToOutput(CString str)
{
	  
str =  _T("\r\n") + str;
CEdit* http_output_editbox = (CEdit*)GetDlgItem(IDC_EDIT_HTTP_OUTPUT);

//在末尾添加内容
int nCount    = 0;
int nLastLineStart = 0;
int nLastLineEnd = 0;
nCount         =  http_output_editbox->GetLineCount();              //获取行数,包括回车行
//MessageBox(nCount);
nLastLineStart    =  http_output_editbox->LineIndex( nCount - 1 );   //获取字符数,许可多行
nLastLineEnd    = nLastLineStart + http_output_editbox->LineLength(nLastLineStart);
http_output_editbox->SetSel( nLastLineEnd + 1, nLastLineEnd + 2 );      //设定光标选中的区域
http_output_editbox->ReplaceSel( str);                 //文字替换

TRACE(L"\nsend [%s] to engine",str);
//MessageBox(str);
}


CString CTG_HelperDlg::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};
			std::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(str, MB_ICONINFORMATION);
                strState = strResponse;
                memset(szChars, 0, BUFFER_SIZE + 1);

            }
			AppendToOutput(str);
            //将多字符转宽字节存为 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;
    }
}

参考:
MFC通过Http Post数据到Web端

MFC发送HTTP请求

你可能感兴趣的:(mfc: http请求get/post)