VC MFC 模拟POST提交

环境:vistual studio 2010旗舰版

第一步:包含头文件 #include "afxinet.h"

void CMyCurlDlg::OnBnClickedBtnStart() {  

// TODO: 在此添加控件通知处理程序代码  

CString host="www.hacktea8.com";  

CString strHost = host;     

CString strUrl = "index.php";     

INTERNET_PORT m_Port = 80;     

CInternetSession m_Session("HttpClient");     

CHttpConnection * m_Server = NULL;     

CHttpFile * m_File = NULL;           

CString strRequest = _T("id=20104833");//提交的数据     

CString strHeader =_T("Content-Type: application/x-www-form-urlencoded\r\n");     

try      {         

m_Server = m_Session.GetHttpConnection(strHost,m_Port);         

if(m_Server == NULL)             

MessageBox("CHttpConnection failed!");    //使用POST方法   

m_File = m_Server->OpenRequest(CHttpConnection::HTTP_VERB_POST,strUrl);         

if (m_File == NULL)             

MessageBox("CHttpFile is NULL!");         

m_File->AddRequestHeaders(strHeader);         

m_File->AddRequestHeaders(_T("Accept-Language: zh-cn"));//特别这个头的部分,如果请求包头错误,那么肯定不会成功。建议:自己网页提交时抓包         

m_File->AddRequestHeaders(_T("Accept-Charset:GB2312"));    //发送头信息 参数        

m_File->SendRequest(strHeader,(LPVOID)(LPCTSTR)strRequest,strRequest.GetLength());                   

DWORD httpStatus;    //获得请求的状态        

m_File->QueryInfoStatusCode(httpStatus);   

CString statusCode;   

statusCode.Format("httpStatus:%d\n",httpStatus);        

MessageBox(statusCode);         

if (httpStatus == HTTP_STATUS_OK)         

{                

CFile file("index.html",CFile::modeCreate|CFile::modeWrite);            

CString strLine;             

int m_read;             

while((m_read = m_File->ReadString(strLine)) > 0)      

file.Write(strLine,strLine.GetLength());                              

   file.Close();         }         

else             

MessageBox("HTTP_STATUS_FAILED\n");     

}      catch (CInternetException* e)      {   

 CString errCode;   

errCode.Format("Error:%d\n",e->m_dwContext);        

MessageBox(errCode);     

}     

if(m_File)         

delete m_File;     

if (m_Server)         

delete m_Server;     

m_Session.Close(); 

}

转载来源:

VC MFC模拟POST提交源码| http://www.hacktea8.com/read-htm-tid-2792-ds-1.html

原文地址:https://www.cnblogs.com/zhongbin/p/3033716.html