1、实验九 HTTP 应用编程一、实验目的:1、了解 HTTP 报文格式及请求主要命令。2、熟悉 HTTP 工作原理。3、熟悉 WinInet 组成实现 HTTP 类及作用。4、掌握 HTTP 应用编程方法。二、主要仪器设备: 硬件:处理器:Pentium 233 MHz 或更高处理器;内存: 128 MB RAM 或更高;硬盘空间:至少 130 MB 可用硬盘空间。 软件:Windows XP、Professional 等操作系统、 VC+.NET2005。三、实验内容:设计一个 HTTP 客户端程序并编码实现:输入服务器地址、网页地址、网 页名称后显示给网页的内容。四、实验步骤及结果:1、主要
2、程序代码:#include “StdAfx.h“#include “MyHTTPClient.h“const int BUF_SIZE = 2048 ;CMyHTTPClient:CMyHTTPClient(void)/ Set the timeout value to 30 secondsm_InternetSession.SetOption (INTERNET_OPTION_CONNECT_TIMEOUT, 1000);m_InternetSession.SetOption (INTERNET_OPTION_RECEIVE_TIMEOUT, 1000);m_InternetSession.
3、SetOption (INTERNET_OPTION_SEND_TIMEOUT, 1000);p_HttpConnection = NULL ;m_hEventKill = CreateEvent (NULL, TRUE, FALSE, NULL);CMyHTTPClient:CMyHTTPClient(void)bool CMyHTTPClient:Download (const CString URLString, CString /打开远程资源文件CStdioFile* pStdioFile = m_InternetSession.OpenURL(URLString);if (pStdi
4、oFile)TCHAR bufferBUF_SIZE = 0;unsigned int nRead = BUF_SIZE;strResponse.Empty();/读取文件while ( (nRead = BUF_SIZE) strResponse += buffer;/关闭远程资源文件pStdioFile-Close ();delete pStdioFile;rr = true ;return rr ;bool CMyHTTPClient:Download (const CString sHost, const int nPort, const CString strObject, CStr
5、ing try/建立HTTP连接p_HttpConnection = m_InternetSession.GetHttpConnection(sHost,(INTERNET_PORT)nPort);/打开远程资源文件CHttpFile* pHttpFile = p_HttpConnection-OpenRequest(CHttpConnection:HTTP_VERB_GET,strObject);if (pHttpFile)DWORD dwRet;pHttpFile-AddRequestHeaders(“Test HTTP“);pHttpFile-SendRequest();/发送请求pHt
6、tpFile-QueryInfoStatusCode(dwRet);/获取该请求的状态号以判断该请求成功与否if (dwRet = HTTP_STATUS_OK)TCHAR bufferBUF_SIZE = 0;unsigned int nRead = BUF_SIZE;strResponse.Empty();/读取文件while ( (nRead = BUF_SIZE) strResponse += buffer;/关闭远程资源文件pHttpFile-Close ();delete pHttpFile;rr = true ;delete p_HttpConnection;catch (CInternetException Ex) /捕获并处理Internet异常AfxMessageBox(“Internet异常“);return rr ;