18,356
社区成员
发帖
与我相关
我的任务
分享
CString URL2FileName(LPCSTR pszURL)
{
CString strFileName(pszURL);
strFileName.Replace(_T("%"),_T("\a"));
strFileName.Replace(_T("<"),_T("%0"));
strFileName.Replace(_T(">"),_T("%1"));
strFileName.Replace(_T("?"),_T("%2"));
strFileName.Replace(_T(":"),_T("%3"));
strFileName.Replace(_T("|"),_T("%4"));
strFileName.Replace(_T("*"),_T("%5"));
strFileName.Replace(_T("/"),_T("%6"));
strFileName.Replace(_T("\""),_T("%7"));
strFileName.Replace(_T("\\"),_T("%8"));
strFileName.Replace(_T("\a"),_T("%9"));
return strFileName;
}
CString FileName2URL(LPCSTR pszFileName)
{
CString strURL(pszFileName);
strURL.Replace(_T("%0"),_T("<"));
strURL.Replace(_T("%1"),_T(">"));
strURL.Replace(_T("%2"),_T("?"));
strURL.Replace(_T("%3"),_T(":"));
strURL.Replace(_T("%4"),_T("|"));
strURL.Replace(_T("%5"),_T("*"));
strURL.Replace(_T("%6"),_T("/"));
strURL.Replace(_T("%7"),_T("\""));
strURL.Replace(_T("%8"),_T("\\"));
strURL.Replace(_T("%9"),_T("%"));
return strURL;
}
int CheckUrl(CHttpFile &chttpurl);//检查网页链接是否有效。
int _tmain(int argc, _TCHAR* argv[])
{
CString URL,URL1; //URL是表示用于打开的网址 URL1表示用于保存该网址源代码的文件的文件名。
CString strTempData;//网页源文件写入一行数据。
CString FileName,FileName1;//FileName1表示文件名。
HANDLE handle;//创建文件操作所保存的句柄。
CInternetSession session(_T("myagent"));//对指定网址爬取所需声明的对象。
URL.Format("%s","http://www.baidu.com/");// 以百度为测试网址。
URL1.Format("%s","http/:////www.baidu.com//");//测试文件名。
FileName1.Format("%s%s",URL1,".TXT");//为文件名后面添加TXT。
const char * LpFileName = FileName1.GetBuffer(0);//返回指向该文件的指针。
//创建文件操作,以写入的方式
handle = ::CreateFileA(FileName1,GENERIC_WRITE,0,NULL,CREATE_NEW,FILE_ATTRIBUTE_NORMAL,NULL);
if(handle == INVALID_HANDLE_VALUE)
return 0;
else
{
CFile file(handle);
CHttpFile *pF=(CHttpFile *)session.OpenURL(URL);
//测试链接是否有效
int statuesCode = CheckUrl(*pF);
switch(statuesCode)
{
case 1: break;
case 0: return 0;
case 400: return 0;
case 404: return 0;
case 500: return 0;
case 503: return 0;
case 405: return 0;
default: return 0;
}//测试链接是否有效。
DWORD NumberOfBytesWritten;//保存已经写入文件的字节数
while (pF->ReadString(strTempData))
{
file.Write(strTempData,strlen(strTempData)+1);
strTempData = "\r\n" + strTempData;
}
}
if(handle)
{
::CloseHandle(handle);
}
session.Close(); //关闭会话
return 0;
}
int CheckUrl(CHttpFile &chttpurl)
{
DWORD dwStatusCode;
if(chttpurl.QueryInfoStatusCode(dwStatusCode))
{
switch(dwStatusCode)
{
case 200: return 1;
case 400: return 400;
case 404: return 404;
case 405: return 405;
case 500: return 500;
case 503: return 503;
default: return 0;
}
}
else
return 0;
}