新人第一篇呵呵 抄的CSDN的一篇文章
不要笑,才开始学MFC,以后技术会好起来的
MFC库的CInternetSession 给我们开发网络程序带来了极大的方便,下面是自己收藏的代码与大家分享
但是CInternetSession有个缺点就是线程多了就报错,但是作为一般应用就足够了。
CString StrHtml= " "; //下载网页后存放的字符串变量
CInternetFile* interFile = NULL; //定义CInternetFile对象
CInternetSession* MySession=new CInternetSession( "xxxxx ",NULL);
/*
网络连接请求时间超时值在数毫秒级。如果连接请求时间超过这个超时值,请求将被取消。
缺省的超时值是无限的。
*/
MySession-> SetOption(INTERNET_OPTION_CONNECT_TIMEOUT,6000);
MySession-> SetOption(INTERNET_OPTION_SEND_TIMEOUT,60000);
MySession-> SetOption(INTERNET_OPTION_RECEIVE_TIMEOUT,60000);
/* 在重试连接之间的等待的延时值在毫秒级。*/
MySession-> SetOption(INTERNET_OPTION_CONNECT_BACKOFF,500);
/* 在网络连接请求时的重试次数。如果一个连接企图在指定的重试次数后仍失败,则请求被取消。 缺省值为5。*/ 以下载
QQ空间歌曲为例
CString DownURL="
http://qq.fxsou.com";
MySession-> SetOption(INTERNET_OPTION_CONNECT_RETRIES, 2);
try
{
interFile=(CInternetFile*)MySession-> OpenURL(DownURL); //关键
}
catch(CException *ex)
{
interFile = NULL;
// pEx-> Delete();
}
try
{
if (interFile)
{
if(interFile-> GetLength() <2) return " ";
}
else
{
return " ";
}
//返回状态
DWORD dwStatusCode;
if( ((CHttpFile *)interFile)-> QueryInfoStatusCode(dwStatusCode))
{
if(dwStatusCode==400)
{
//AfxMessageBox( "400 ");
return " ";
}
}
else
{
return " ";
}
CString StrLine;
long Num_Line=1;
while (interFile-> ReadString(StrLine)!=NULL)
{
if(Num_Line % 300) Sleep(1);
StrHtml += StrLine + "\r\n "; //换行处理
Num_Line=Num_Line+1;
}
}
else
{
return " ";
}
}
catch(CException *ex)
{
}
interFile-> Close();
delete interFile;
return StrHtml; //返回下载网页的结果