How can i check to see if a JPG url exists before downloading it, to avoid an exception?
procedure TForm1.Button1Click(Sender: TObject);
var
FS: TFileStream;
Url, FileName: String;
I, C: Integer;
begin
for I := 1 to 1000 do
begin
Url := 'http://www.mysite.com/images/' + IntToSTr(I) + '/Image.jpg';
FileName := 'C:\Images\' + IntToStr(I) + '.jpg';
FS := TFileStream.Create(FileName, fmCreate);
try
try
IdHTTP1.Get(Url);
c := IdHTTP1.ResponseCode;
if C = 200 then
IdHTTP1.Get(Url, FS);
except
end;
Application.ProcessMessages;
finally
Fs.Free;
end;
end;
end;
To answer your main question, the only way you have to check if a particular URL is valid or not is to check against the web server and check what the server tells you.
With indy you can use the AIgnoreReplies
parameter of the Get and other methods to instruct the TIdHTTP instance not to raise an exception in case that status is returned by the web server, like this:
IdHTTP1.Get(Url, FS, [404]);
A exception will still be raised in case any status different than 200 and 400. There are other status codes that may don't raise an exception depending on various configurations of the component, for example status code 401 and authentication parameters, and others.
That said, I find several problems in your code:
EOutOfMemory
than a EIdSocketError
, EIdHTTPProtocolException
or even a EMayanWorldEnd
exception!GET
command over it, perform a HEAD
one!