MFC下http连接网络(get方法)

来源:互联网 发布:windows nt 6.2 编辑:程序博客网 时间:2024/05/16 07:31

MFChttp连接网络

 

1.         初始化

#include"afxsock.h"

BOOLCHttpClinetDlg::OnInitDialog()

{

 

      // TODO: Add extra initialization here

      if(AfxSocketInit(NULL)==FALSE)

      {

             AfxMessageBox("Socket InitError");

      }

 

      return TRUE;  // return TRUE  unless you set the focus to a control

}

2.         连接网站,获取信息

voidCHttpClinetDlg::OnGet()

{

      // TODO: Add your control notificationhandler 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);

}

 

BOOLCHttpClinetDlg::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("MyWriteFileerror::"));

             return FALSE;

      }

 

      file.SeekToEnd();  

      file.Write(buffer,len);

      file.Close();

      return TRUE;

 

}

3.         结束