现在位置:
首页 >
C/C++ > C++的post请求(使用的是CInternetSession)
C++的post请求(使用的是CInternetSession)
// WebPost.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
//int _tmain(int argc, _TCHAR* argv[])
//{
// return 0;
//}
#include <iostream>
#include <string>
#include <afxinet.h> //定义了MFC CInternetSession类等
bool PostHttpPage(const CString& hostName, const CString& pathName, const std::string& postData)
{
using namespace std;
CInternetSession session(_T("your app agent name"));
try
{
INTERNET_PORT nPort = 80;
DWORD dwRet = 0;
CHttpConnection* pServer = session.GetHttpConnection(hostName, nPort);
CHttpFile* pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST, pathName);
CString strHeaders = _T("Content-Type: application/x-www-form-urlencoded"); // 请求头
//开始发送请求
pFile->SendRequest(strHeaders,(LPVOID)postData.c_str(),postData.size());
pFile->QueryInfoStatusCode(dwRet);
if (dwRet == HTTP_STATUS_OK)
{
CString result, newline;
while(pFile->ReadString(newline))
{
//循环读取每行内容
result += newline+"\r\n";
}
std::cout<<result<<std::endl;//显示返回内容
}
else
{
return false;
}
delete pFile;
delete pServer;
}
catch (CInternetException* pEx)
{
//catch errors from WinInet
TCHAR pszError[200];
pEx->GetErrorMessage(pszError, 200);
std::cout<<pszError<<std::endl;//显示异常信息
return false;
}
session.Close();
return true;
}
int main(void)
{
//向http://current.sinaapp.com/post.php发送数据
PostHttpPage(_T("current.sinaapp.com"),_T("post.php"),"name=rain&age=12");
}