Главная страница
Top.Mail.Ru    Яндекс.Метрика
Текущий архив: 2006.01.08;
Скачать: CL | DM;

Вниз

InternetReadFile как проверить ошибку???   Найти похожие ветки 

 
Санек ©   (2005-09-22 17:38) [0]

Скачиваем файлик с помощью InternetReadFile, а сервер выдает ошибку... и эта ошибка сохраняется в файл как HTML. Как узнать, что произошла ошибка и при этом файл не качать?

function SaveFile(const FileName, URL: String): Boolean;
const
 bInitalRequest : bool = TRUE;
type
 tBuf = array [1..1024] of char;
var
 hConnect, InetHandle: HInternet;
 f: File;
 b : bool;
 dwCode: ^DWORD;
 dwSize: DWORD;
 DUMMY : DWORD;
 dwError, szError: DWORD;
 dwLength, dWritten :DWORD;
 szBuffer: ^tBuf;
 err: Array [1..1024] of char;
begin
 New (dwCode);
 New (szBuffer);
 InetHandle := InternetOpen(PChar(Application.Title),
                            INTERNET_OPEN_TYPE_PRECONFIG,
                            nil,
                            nil,
                            INTERNET_FLAG_KEEP_CONNECTION);
//  bSend := HttpSendRequest(hRequest, NULL,0, NULL,0);

 hConnect := InternetOpenUrl (InetHandle, PChar(URL), nil, 0,
                                    INTERNET_FLAG_DONT_CACHE or
                                    INTERNET_FLAG_KEEP_CONNECTION or
                                    INTERNET_FLAG_RELOAD, 0);

 if not bInitalRequest then
   if not HttpSendRequest (hConnect, nil, 0, nil, 0) then ShowMessage ("Error: HttpSendRequest");
 dwSize:= sizeof(dwCode^);
 if not InternetQueryOption (hConnect, INTERNET_OPTION_HANDLE_TYPE,
                       dwCode, dwSize) then ShowMessage ("Error: InternetQueryOption");
 if ( (dwCode^ = INTERNET_HANDLE_TYPE_HTTP_REQUEST)  or
      (dwCode^ = INTERNET_HANDLE_TYPE_CONNECT_HTTP) ) then
 begin
   dwSize := sizeof (DWORD) ;
   if not HttpQueryInfo (hConnect, HTTP_QUERY_STATUS_CODE or HTTP_QUERY_FLAG_NUMBER,
                        dwCode, dwSize, DUMMY)
   then
   if dwCode^ = HTTP_STATUS_PROXY_AUTH_REQ then
   begin
     ShowMessage ("Auth Required!");
   end;
 end;
 if dwCode^ <> HTTP_STATUS_PROXY_AUTH_REQ then
 begin
   AssignFile(f, FileName);
   Rewrite(f,1);
   while true do
   begin
      dwLength := SizeOf (szBuffer^);
      if not InternetReadFile (hConnect, szBuffer, dwLength, dWritten) then
      begin
        ShowMessage ("ERROR: InternetReadFile");
        break;
        CloseFile(f);
        DeleteFile(FileName);
      end;
      if dWritten = 0 then break
      else
      begin
        BlockWrite(f, szBuffer^, dWritten);
      end;
   end;
   CloseFile(f);
   Result := True;
 end;
 InternetCloseHandle(InetHandle);
 Dispose (dwCode);
 Dispose (szBuffer);
end;



 
Digitman ©   (2005-09-22 17:51) [1]


> эта ошибка сохраняется в файл как HTML


ой врешь ведь !

покажи строчку своего кода, где помимо твоей воли в файл сохраняется некая т.н. "ошибка" ..


 
Санек ©   (2005-09-22 17:53) [2]

В файл сохраняется вот это:


The page cannot be found
The page you are looking for might have been removed, had its name changed, or is temporarily unavailable.

--------------------------------------------------------------------------------

Please try the following:

If you typed the page address in the Address bar, make sure that it is spelled correctly.

Open the file:// home page, and then look for links to the information you want.
Click the Back button to try another link.
HTTP 404 - File not found
Internet Information Services

--------------------------------------------------------------------------------

Technical Information (for support personnel)

More information:
Microsoft Support


 
Digitman ©   (2005-09-22 18:09) [3]

это (т.е. приведенное тобой) с т.з. ф-ции InternetReadFile() НЕ является какой-то там ошибкой  - ф-ция InternetReadFile() исправно выполнила свое предназначение и прочитала/записала то что ты попросил


 
Санек ©   (2005-09-22 18:11) [4]

Эт я понимаю, а как мне сделать чтобы т.з. моей всё было как надо???

я же писал, что сервер выдает ошибку и вопрос в том, как мне её обработать и не закачивать файл?


 
Санек ©   (2005-09-23 10:26) [5]

Ув. знатоки, подскажите плз......


 
isasa ©   (2005-09-23 10:55) [6]

Юзаем HttpQueryInfo

var hHTTP : HInternet;
...
   bLen, hInd : longword;
   i : integer;

 bLen:=4;
 hInd:=0;
 HttpQueryInfo(hHTTP, HTTP_QUERY_STATUS_CODE or HTTP_QUERY_FLAG_NUMBER, @i, bLen, hInd);
 Result:=i; // 200 Все нормально, ..........


 
Санек ©   (2005-09-23 11:00) [7]

А у меня оно почему-то всегда равно 13, где же вкралась ошибка??? Может потому что запрос идет через прокси???


 
isasa ©   (2005-09-23 11:18) [8]

STATUS_CODE от прокси не зависит.


 
Санек ©   (2005-09-23 11:30) [9]

А почему у меня всегда 13, а не 200, даже когда файл нормально скачивается без ошибки???


 
isasa ©   (2005-09-23 11:35) [10]

Попробуй так,

var buff: string;
   rBuff : PChar;

...
 rBuff:=StrAlloc(2048);
 hInd:=0;
 bLen:=2048;
 HttpQueryInfo(hHTTP, HTTP_QUERY_RAW_HEADERS_CRLF, rBuff, bLen, hInd);
 buff:=string(rBuff);

и посмотри содержимое буфера (buff).


 
Санек ©   (2005-09-23 12:37) [11]

Спасибо, всё получилось. Код функции:

function DownloadFile(const URL, FileName: String): Boolean;
type
 TBuffer = Array [1..1024] of Char;
var
 F: File;
 szWrite: Integer;
 Buffer: ^TBuffer;
 hSession, hURL: HINTERNET;
 dwSize, dwInd, dwStatus: DWORD;
begin
 Result := False;
 hSession := InternetOpen(PChar(Application.Title),
                            INTERNET_OPEN_TYPE_PRECONFIG,
                            nil,
                            nil,
                            INTERNET_FLAG_KEEP_CONNECTION);
 if Assigned(hSession) then
 try
   hURL := InternetOpenUrl (hSession, PChar(URL), nil, 0,
                            INTERNET_FLAG_DONT_CACHE or
                            INTERNET_FLAG_KEEP_CONNECTION or
                            INTERNET_FLAG_RELOAD, 0);
   if Assigned(hURL) then
   try
     dwSize := SizeOf(dwStatus);
     dwInd := 0;
     if HttpQueryInfo(hURL, HTTP_QUERY_STATUS_CODE or
                            HTTP_QUERY_FLAG_NUMBER,
                            @dwStatus, dwSize, dwInd)
        and (dwStatus = HTTP_STATUS_OK) then
     begin
       dwSize := SizeOf(Buffer^);
       AssignFile(F, FileName);
       Rewrite(F, 1);
       New(Buffer);
       try
         Result := True;
         szWrite := 0;
         while True do
         begin
           Result := InternetReadFile (hURL, Buffer, dwSize, dwInd);
           if Result and (dwInd > 0) then
             BlockWrite(f, Buffer^, dwInd, szWrite)
           else
             break;
         end;
         Result := Result and (szWrite > 0);
       finally
         CloseFile(F);
         Dispose(Buffer);
         if not Result then DeleteFile(FileName);
       end;
     end;
   finally
     InternetCloseHandle(hURL);
   end;
 finally
   InternetCloseHandle(hSession);
 end;
end;



Страницы: 1 вся ветка

Текущий архив: 2006.01.08;
Скачать: CL | DM;

Наверх




Память: 0.51 MB
Время: 0.019 c
9-1122891585
Dr.Nemo
2005-08-01 14:19
2006.01.08
Реализация на стороне игры


2-1135082307
ZbarKiy
2005-12-20 15:38
2006.01.08
RGB ?


3-1132020467
fedor
2005-11-15 05:07
2006.01.08
FibPlus: проблеммы соединения с базой *.gdb


6-1127529214
antoxa2005
2005-09-24 06:33
2006.01.08
Странно, почему мой сканер портов не видит мой порт?


10-1111013938
val_5
2005-03-17 01:58
2006.01.08
Как работать с TwebConnection ?