欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MFC实现http连接、发送和接收数据

程序员文章站 2023-02-14 22:52:45
以上为伪代码示范过程。 ......
	#include <afxinet.h>
	// 设置超时
	cinternetsession session;
	session.setoption(internet_option_connect_timeout, 2000);
	session.setoption(internet_option_connect_retries, 3);
	session.setoption(internet_option_send_timeout, 10000);
	session.setoption(internet_option_receive_timeout, 20000);
	// 打开http连接
	chttpconnection *phttpconnection = session.gethttpconnection(strhost, internet_flag_keep_connection, iport);
	if (null == phttpconnection) 
	{
		return false;
	}
	// 开启一个http请求
	chttpfile *phttpfile = phttpconnection->openrequest(_t("post"), strrequesturl,	null, 1, null, null, internet_flag_keep_connection);
	if (null == phttpfile) {
		return false;
	}
	// 设置http请求包头
	phttpfile->addrequestheaders(_t("user-agent: myproduct/1.0.0 (windows)"));
	phttpfile->addrequestheaders(_t("content-type: application/octet-stream"));  
	phttpfile->addrequestheaders(_t("charset: utf-8"));
	// 发送数据
	bool bresult = phttpfile->sendrequest(null, 0, (lpvoid)output.data(), (dword)output.length());
	if (!bresult) {
		return false;
	}
	// 查询状态
	dword dwhttpcode = 0;
	bresult = phttpfile->queryinfostatuscode(dwhttpcode);
	if (!bresult)
	{
		return false;
	}
	// 出错的原因
	if ((dwhttpcode < 200) || (dwhttpcode >= 300))
	{
		bool bresult = phttpfile->queryinfo(http_query_status_text, szbuffer, &dwbuffersize);
	}
	// 接收响应
	while ((nreadbytes = phttpfile->read((void*)szbuffer, 4096)) > 0) 
	{
		buffer.write(szbuffer, nreadbytes);
		memset(szbuffer, 0, 4096 * sizeof(char));
	}
	// 释放资源
	if (null != phttpfile) {
		phttpfile->close();
		delete phttpfile;
		phttpfile = null;
	}
	if (null != phttpconnection) {
		phttpconnection->close();
		delete phttpconnection;
		phttpconnection = null;
	}
	session.close();

 以上为伪代码示范过程。