Function FileComm.GetWebPage(const Url: string) : string;      (*获取网页源文件*)
var
    Session, HttpFile : HINTERNET;
    szSizeBuffer : Pointer;
    dwLengthSizeBuffer : DWord;
    dwReserved : DWord;
    dwFileSize : DWord;
    dwBytesRead : DWord;
    Contents : PChar;
begin
    Session := InternetOpen('',0,niL,niL,0);
    HttpFile := InternetOpenUrl(Session,PChar(Url),niL,0,0,0);
    dwLengthSizeBuffer := 1024;
    HttpQueryInfo(HttpFile,5,szSizeBuffer,dwLengthSizeBuffer,dwReserved) ;    GetMem(Contents, dwFileSize);
    InternetReadFile(HttpFile,Contents,dwFileSize,dwBytesRead) ;    InternetCloseHandle(HttpFile);
    InternetCloseHandle(Session);
    Result := UTF8Decode(StrPas(Contents));
    FreeMem(Contents);
end;函数代码如上。
问题是,不知道如何设置超时时间,不设置的话,当请求的网址不存在,程序就死在那不动了。这个函数有时候读出来的源文件后面会加上一些乱码的字符,有办法解决吗?或者谁有更好的读取源文件的函数。借俺用下。

解决方案 »

  1.   

    用Indy里的IdHTTP组件。直接IdHttp.Get。
      

  2.   

    至于你为何会乱码,因为PChar指向以'\0'为结尾的字符串,你申请内存后要把那段内存置0。
      

  3.   

    加try...except...块进行异常处理。
      

  4.   

            IdHttp := TIdHTTP.Create(nil);
            IdHttp.ReadTimeout :=20000;
            IdHttp.Request.UserAgent:='Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705 )';        try
                    GetRemoteStr := IdHttp.Get(Url);        
            except
                    on E: Exception do
                    begin
                            if Pos('Not Found',E.Message)>0 then
                            begin
                                    GetRemoteStr := 'error:not found';
                            end
                            else
                                    GetRemoteStr := 'error:'+ E.Message;                end;
            end;
            IdHttp.Destroy;
      

  5.   

    IDHttp.ReadTimeout :=20000 毫秒计算