MFC网页访问的实现示例

本示例使用MFC 类CInternetSession 建立连接,使用 CHttpFile读取内容。


首先,建立一个MFC对话框项目,界面如下:

MFC网页访问的实现示例

1. 添加头文件:

 

#include <afxinet.h>



2. UTF-8 转 UNICODE:

 

 

int cU8xU(wchar_t* pOut,char *pText)

{

	int ret = 0; 

	char* uchar = (char *)pOut; 

	unsigned cIn = (unsigned char)pText[0]; 

	if(cIn<0x80){ // ASCII 0x00 ~ 0x7f 

		pOut[0] = pText[0]; 

	}else if(cIn<0xdf){ 

		uchar[0] = (pText[0]<<6)|(pText[1]&0x3f); 

		uchar[1] = (pText[0]>>2)&0x0f; 

		ret = 1; 

	}else if(cIn<=0xef){ 

		uchar[0] = (pText[1]<<6)|(pText[2]&0x3f); 

		uchar[1] = (pText[0]<<4)|((pText[1]>>2)&0x0f); 

		ret = 2; 

	}else if(cIn<0xf7){ 

		uchar[0] = (pText[2]<<6)|(pText[3]&0x3f); 

		uchar[1] = (pText[1]<<4)|((pText[2]>>2)&0x0f); 

		uchar[2] = ((pText[0]<<2)&0x1c)|((pText[1]>>4)&0x03); 

		ret = 3; 

	} 

	return ret; 

}

int sU8xU(WCHAR* pOut,char *pText,int Len){ 

	int i,j; 

	for(i=0,j=0;i<Len;i++,j++){ 

		i+=cU8xU(&pOut[j],&pText[i]); 

	} 

	return j; 

}



3. 加入按键响应函数:

 

 

void CURL_TESTDlg::OnBnClickedButton1()

{

//#include <afxinet.h>

	CString url;

	GetDlgItem(IDC_EDIT1)->GetWindowText(url); 



	DWORD code = 0;

	CInternetSession httpSession ; 

	CHttpFile * htmlFile=NULL ;



	try{

		//打开网页 

		htmlFile=(CHttpFile*)httpSession.OpenURL(_T("http://www.sogou.com/")); 

		

		//htmlFile=(CHttpFile*)httpSession.OpenURL(url);

		htmlFile->QueryInfoStatusCode(code);

	}catch(...)

	{

		MessageBox(_T("err"),_T("BE"),1); // 如果断网而打不开这个网址,并且不抓取这个错误,就会弹出一个提示系统提示框!这里我自己处理。



		return;

	}



	//读取网页数据 

	CString str;

	CString info=_T("");

	while(htmlFile->ReadString(str))

	{   

		info+=str ;

	}



	//释放

	htmlFile->Close();

	httpSession.Close();



	//显示

	CString result;

	int length = info.GetLength();

	char *ab = new char[length];

	memset(ab, 0, length);

	memcpy(ab, info.GetBuffer(), length);

	WCHAR *big = new WCHAR[length];

	memset(big, 0, length);

	int len = sU8xU(big, ab, length);

	big[len] = '\0';

	delete []ab;

	

	CString temp(big);



	result.Format("The return code(返回值): %d\r\n %s", code, temp.GetBuffer());



	GetDlgItem(IDC_EDIT2)->SetWindowText(result); 

	//delete []big; // i don't how to do for this.

}



4. 另外也可以使用这段粗糙的代码实现这个功能:

 

 

	CInternetSession mysession;

	CHttpConnection *myconn=mysession.GetHttpConnection("www.veno2.com");



	CHttpFile *myfile=myconn->OpenRequest("GET","/ag_list");

	myfile->SendRequest();



	CString mystr;

	CString tmp;

	while(myfile->ReadString(tmp))

	{

		mystr+=tmp;

	}

	//GetDlgItem(IDC_EDIT2)->SetWindowText(mystr); 



	myfile->Close();

	myconn->Close();

	mysession.Close();

	delete myfile;

	delete myconn;

	myfile=0;

	myconn=0;


 


 

你可能感兴趣的:(mfc)