您的位置:首页 > 编程语言 > C语言/C++

C++ 发送POST请求

2013-10-29 21:12 183 查看
今天看了下关于MFC环境下的网络交互问题,发送POST请求的方法。在网上看了下别人的资料,在这里转载记录下,下面函数代码摘自CSDN论坛biweilun的帖子。

本来是想借用搜狗实验室的分析系统,想用post请求响应的php返回相应的结果,但是有跨域访问问题,无奈之下只好先把问题放放,等其他作业写完之后再来看看。

#include "afxinet.h"

/* 发送post请求
第一个参数为URL头
第二个参数为要post表单的内容
第三个参数用于保存页面返回的信息
第四个参数用于记录日志
*/
bool PostContent(CString strUrl, const CString &strPara, CString &strContent, CString &strDescript)
{
try{
strDescript = "提交成功完成!";
bool bRet = false;
CString strServer, strObject, strHeader, strRet;
unsigned short nPort;
DWORD dwServiceType;
if(!AfxParseURL(strUrl, dwServiceType, strServer, strObject, nPort))
{
strDescript = strUrl + "不是有效有网络地址!";
return false;
}
CInternetSession sess;//Create session

CHttpFile* pFile;

CHttpConnection *pServer = sess.GetHttpConnection(strServer, nPort);

if(pServer == NULL)
{
strDescript = "对不起,连接服务器失败!";
return false;
}
pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST,strObject,NULL,1,NULL,NULL,INTERNET_FLAG_EXISTING_CONNECT);
if(pFile == NULL)
{
strDescript = "找不到网络地址" + strUrl;
return false;
}

CString strHeaders = _T("Content-Type:application/x-www-form-urlencoded;Access-Control-Allow-Origin:http://www.sogou.com");
pFile -> SendRequest(strHeaders, (LPTSTR)(LPCTSTR)strPara, strPara.GetLength());

CString strSentence;
DWORD dwStatus;
DWORD dwBuffLen = sizeof(dwStatus);
BOOL bSuccess = pFile->QueryInfo(
HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER,
&dwStatus, &dwBuffLen);

if( bSuccess && dwStatus>=  200 && dwStatus<300)
{
char buffer[256];
memset(buffer, 0, 256);
int nReadCount = 0;
while((nReadCount = pFile->Read(buffer, 2048)) > 0)
{
strContent += buffer;
memset(buffer, 0, 256);
}
bRet = true;
}
else
{
strDescript = "网站服务器错误" + strUrl;
bRet = false;
}
////////////////////////////////////////
pFile->Close();
sess.Close();
return bRet;
}
catch(...)
{
int nCode = GetLastError();
strDescript.Format("向服务器post失败!错误号:%d", nCode);
return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: