Delphi实现判断网址是否存在及是否可以打开的方法
本例所述Delphi程序用于检测网址是否为404,也就是检测网址是否存在,或是否可以打开,针对不同的检查方法,会返回不同的结果。
程序主要代码如下:
unitaddress; interface uses Windows,Messages,SysUtils,Classes,Graphics,Controls,Forms,Dialogs, Psock,NMHttp,StdCtrls,ComCtrls; type TForm1=class(TForm) Label1:TLabel; Edit1:TEdit; Button1:TButton; NMHTTP1:TNMHTTP; StatusBar1:TStatusBar; procedureButton1Click(Sender:TObject); procedureNMHTTP1Success(Cmd:CmdType); procedureNMHTTP1Failure(Cmd:CmdType); procedureNMHTTP1HostResolved(Sender:TComponent); procedureNMHTTP1InvalidHost(varHandled:Boolean); procedureNMHTTP1AuthenticationNeeded(Sender:TObject); procedureNMHTTP1Connect(Sender:TObject); procedureNMHTTP1ConnectionFailed(Sender:TObject); procedureFormActivate(Sender:TObject); procedureFormClose(Sender:TObject;varAction:TCloseAction); procedureNMHTTP1Redirect(varHandled:Boolean); procedureEdit1KeyDown(Sender:TObject;varKey:Word; Shift:TShiftState); private {Privatedeclarations} public {Publicdeclarations} end; var Form1:TForm1; implementation {$R*.DFM} procedureTForm1.Button1Click(Sender:TObject); var url:string; begin url:=Edit1.Text; StatusBar1.simpletext:='正在检验'; NMHTTP1.Head(url); end; procedureTForm1.NMHTTP1Success(Cmd:CmdType); begin casecmdof CmdHEAD: StatusBar1.SimpleText:='网址正确' end; end; procedureTForm1.NMHTTP1Failure(Cmd:CmdType); begin casecmdof CmdHEAD: StatusBar1.SimpleText:='网址不正确,没有这个页面' end; end; procedureTForm1.NMHTTP1HostResolved(Sender:TComponent); begin StatusBar1.SimpleText:='正确解析主机名'; end; procedureTForm1.NMHTTP1InvalidHost(varHandled:Boolean); begin StatusBar1.SimpleText:='不能解析主机名'; end; procedureTForm1.NMHTTP1AuthenticationNeeded(Sender:TObject); begin StatusBar1.SimpleText:='需要身份验证'; end; procedureTForm1.NMHTTP1Connect(Sender:TObject); begin StatusBar1.SimpleText:='连接到主机'; end; procedureTForm1.NMHTTP1ConnectionFailed(Sender:TObject); begin StatusBar1.SimpleText:='连接主机失败'; end; procedureTForm1.FormActivate(Sender:TObject); begin Edit1.Text:='http://www.'; end; procedureTForm1.FormClose(Sender:TObject;varAction:TCloseAction); begin NMHTTP1.Destroy; end; procedureTForm1.NMHTTP1Redirect(varHandled:Boolean); begin StatusBar1.SimpleText:='重定向到其它页面'; end; procedureTForm1.Edit1KeyDown(Sender:TObject;varKey:Word; Shift:TShiftState); begin ifKey=VK_RETURNthen begin StatusBar1.simpletext:='正在检验'; NMHTTP1.Head(Edit1.Text); end; end; end.