⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 httpcommand.cpp

📁 http发送文件头 可以设置cookie等。 还可以做比较复杂的通讯
💻 CPP
字号:
#include "stdafx.h"
#include "HTTPCommand.h"
#include "RegMan.h"

CHTTPCommand::CHTTPCommand(HINTERNET hConnection, bool bPresetAttributes):m_hConnection(hConnection)
{
	m_hSession = NULL;
	if(bPresetAttributes)
	{
/*		m_Attributes[_T("X-CLIENTID")] = CRegRoot::SenderID();
		m_Attributes[_T("X-VERSION")] = CRegRoot::Version();
		m_Attributes[_T("X-USERTYPE")] = CRegRoot::UserType();
*/	}
}

CHTTPCommand::~CHTTPCommand(void)
{
	if(m_hSession != NULL)
		InternetCloseHandle(m_hSession);
}
	
void CHTTPCommand::SetRequestAttribute(CString sName, CString sValue)
{
	m_Attributes[sName] = sValue;

}



CString CHTTPCommand::AttributesToString()
{
	CString sHeaders;
	
	int idx = 0;
	POSITION pos = m_Attributes.GetStartPosition();
	while(pos != NULL)
	{
		CString sName = m_Attributes.GetKeyAt(pos);
		CString sValue = m_Attributes.GetValueAt(pos);
		
		if( sValue.GetLength() == 0 ) sValue = "0";
		if(idx > 0)
			sHeaders += _T("\r\n");
		
		sHeaders += sName;
		sHeaders += _T(":");
		sHeaders += sValue;

		m_Attributes.GetNext(pos);
		idx ++;
	}

	return sHeaders;
}

int CHTTPCommand::Execute(CString sUrl, bool bAutoFlush)
{
	CString sHeaders = AttributesToString();
	DWORD dwHeaders = sHeaders.GetLength();
	m_hSession = InternetOpenUrl(m_hConnection, sUrl, sHeaders, dwHeaders, 
			INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_RELOAD, 0);
	if(m_hSession == NULL)
		return 0;

	DWORD dwCode = 0;
	DWORD dwSize = sizeof(DWORD);
	DWORD dwIndex = 0;
	if(!HttpQueryInfo(m_hSession, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER,
			&dwCode, &dwSize, &dwIndex))
		return 0;

	DWORD dw = GetLastError();

	if((dwCode < 200) || (dwCode > 300))
		return 2;


	return 1;											//0:服务器响应正确,0
}

CString CHTTPCommand::GetResponseAttribute(CString sName)
{
	TCHAR szBuffer[2049] = {0};
	DWORD dwSize = 2048 * sizeof(TCHAR);
	DWORD dwIndex = 0;
	lstrcpy(szBuffer, sName);

	if((m_hSession != NULL) &&
			HttpQueryInfo(m_hSession, HTTP_QUERY_CUSTOM, (LPVOID) szBuffer, &dwSize, &dwIndex))
		return szBuffer;
	else
		return _T("2");
}


CString CHTTPCommand::GetBody()
{
	DWORD dwNumberOfBytesRead;
	char sz[2048];
	int result;
	CString strRcv = "";
	if(m_hSession == NULL)
		return "";
	do
	{
		
		result = InternetReadFile(m_hSession, sz, 2047, &dwNumberOfBytesRead);
		sz[dwNumberOfBytesRead] = '\0';
		int x = strlen(sz);
		strRcv += sz;
		memset(sz, 0, 2048);

	} while(result && dwNumberOfBytesRead != 0);
	return strRcv;
}

void CHTTPCommand::Close()
{
	if(m_hSession != NULL)
	{
		InternetCloseHandle(m_hSession);
		m_hSession = NULL;
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -