1、包含头文件
#include<afxinet.h>
2、建立CInternetSession的实列CInternetSession mysession;
3、调用CInternetSession::GetHttpConnection,创建CHttpConnection对象并返回其指针
CHttpConnection *myconn=mysession.GetHttpConnection(L"192.168.31.129",INTERNET_FLAG_KEEP_CONNECTION,\
INTERNET_INVALID_PORT_NUMBER,NULL, NULL);
4、OpenRequest和SendRequest一起工作打开文件。OpenRequest去创建个请求句柄并且把参数存储在句柄中。SendRequest把请求参数送到HTTP服务器
CHttpFile *myfile=myconn->OpenRequest(L"GET",L"/cgi-bin/yuanhui.html",NULL, 1, NULL,\ NULL,INTERNET_FLAG_KEEP_CONNECTION);
myfile->SendRequest(NULL, 0 , NULL, 0);
5、读取字节流
CString tmp;
CString mystr;
while(myfile->ReadString(tmp))
{
mystr+=tmp;
}
如果出现乱码,可以通过以下方式解决:
(1)、转码:详见MultiByteToWideChar函数
char *pStr = (char *)str.GetBuffer(str.GetLength()); //取得str对象的原始字符串
int nBufferSize = MultiByteToWideChar(CP_ACP, 0, pStr, -1, NULL, 0); //取得所需缓存的多少
wchar_t *pBuffer = (wchar_t*)malloc(nBufferSize * sizeof(wchar_t));//申请缓存空间
MultiByteToWideChar(CP_ACP, 0, pStr, -1 , pBuffer, nBufferSize*sizeof(wchar_t));//转码
AfxMessageBox(pBuffer);
(2)、用read读取:(不知原因为何?望高手指点)
char buf[1024];
//memset函数,初始化
memset(buf, NULL, 1024);
if (myfile){
myfile->Read(buf, 1024);
}
MessageBox(CString(buf));
将数据存储在myfile文件中
6、清理
myfile->Close();
myconn->Close();
mysession.Close();
delete myfile;
delete myconn;
myfile=0;
myconn=0;
如果,使用了转码的方法,还需要增加
free(pBuffer);