江湖博客

青春是一个充满活力的季节,即便是我们失去了天使的翅膀,只要我们还有一颗青春的心,那么我们的生活依然能够如阳光般灿烂!......
现在位置:首页 > C/C++ > C++的post请求(使用的是CInternetSession)

C++的post请求(使用的是CInternetSession)

very168    C/C++    2018-11-7    1993    0评论
// 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"); 
}

评论一下分享本文赞助博瑞

赞助博瑞X

扫码赞助博瑞
联系站长
江湖博客
挤眼 亲亲 咆哮 开心 想想 可怜 糗大了 委屈 哈哈 小声点 右哼哼 左哼哼 疑问 坏笑 赚钱啦 悲伤 耍酷 勾引 厉害 握手 耶 嘻嘻 害羞 鼓掌 馋嘴 抓狂 抱抱 围观 威武 给力
提交评论

清空信息
关闭评论