目的是获取网站的其中一个数据:
/* CInternetSession session("Internet Explorer", 0);//创建Internet会话
CHttpFile* pHttpFile=NULL; //网页文件
m_lotteryURL="http://www.lottery.gov.cn/";
CString content,strTemp;
try
{
//获取已经打开的网页代码文件
pHttpFile = (CHttpFile*)session.OpenURL(m_lotteryURL,INTERNET_FLAG_TRANSFER_ASCII | INTERNET_FLAG_RELOAD|INTERNET_FLAG_DONT_CACHE);
}
catch (CInternetException* e)
{
e->ReportError();
delete e;
}
//一行行读取网页的内容,并组合出完整
while (pHttpFile->ReadString(strTemp))
{
content +=strTemp + TEXT("\r\n");
}
int startIndex=content.Find("index_plw_term");
strTemp=content.Mid(startIndex,256);
AfxMessageBox(strTemp);
pHttpFile->Close();
delete pHttpFile;
session.Close();
*/
但是这样获取的好像是源码,不是访问结果
相关网站:
http://www.lottery.gov.cn/
你获取的是字符串当然是这样,你要用解析引擎进行解析 比如IE,才能输出你说的结果,在MFC中,你可以使用webbrower控件
本示例使用MFC 类CInternetSession 建立连接,使用 CHttpFile读取内容。
首先,建立一个MFC对话框项目,界面如下:
#include
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 pOut[0] = pText[0];
}else if(cIn uchar[0] = (pText[0] uchar[1] = (pText[0]>>2)&0x0f;
ret = 1;
}else if(cIn<=0xef){
uchar[0] = (pText[1]< uchar[1] = (pText[0]>2)&0x0f);
ret = 2;
}else if(cIn uchar[0] = (pText[2] uchar[1] = (pText[1]>2)&0x0f);
uchar[2] = ((pText[0]<>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
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;