MFC 下 http 连接网络
1. 初始化
#include "afxsock.h"
BOOL CHttpClinetDlg::OnInitDialog()
{
// TODO: Add extra initialization here
if(AfxSocketInit(NULL)==FALSE)
{
AfxMessageBox("Socket Init Error");
}
return TRUE; // return TRUE unless you set the focus to a control
}
2. 连接网站,获取信息
void CHttpClinetDlg::OnGet()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
CInternetSession mySession(NULL,0);
CHttpFile* myHttpFile=NULL;
Cstring m_URL = “163.com”;
m_infor="link net :: "+m_URL+"/r/n";
UpdateData(false);
CString myData;
myHttpFile=(CHttpFile*)mySession.OpenURL(m_URL);
Cstring temp;
while(myHttpFile->ReadString(myData))
{
temp.Format("realLen = %d", myData.GetLength());
if (myData.GetLength())
{
MyWriteFile((BYTE*)myData.GetBuffer(myData.GetLength()), myData.GetLength());
myData.ReleaseBuffer();
}
m_infor=m_infor+"/r/n";
m_infor+=myData;
}
myHttpFile->Close();
mySession.Close();
UpdateData(false);
}
BOOL CHttpClinetDlg::MyWriteFile(BYTE *buffer, int len)
{
CFile file;
CFileException e;
CString path= "";
GetModuleFileName(NULL,path.GetBuffer(MAX_PATH),MAX_PATH);
path.ReleaseBuffer();
path = path.Left(path.ReverseFind('//'));
path += "//";
path += "SaveData.txt";
if( !file.Open( path, CFile::modeCreate | CFile::modeNoTruncate | CFile::modeWrite, &e ) )
{
//´íÎó
AfxMessageBox(_T("MyWriteFile error::"));
return FALSE;
}
file.SeekToEnd();
file.Write(buffer,len);
file.Close();
return TRUE;
}
3. 结束