2012-02-11 19 views
7

non mi importa se si tratta di una stringa, stringlist, memo, ecc ... ma non un file su discoCome scaricare una pagina Web in una variabile?

Come faccio a scaricare una pagina web competere in una variabile? Grazie

+1

possibile duplicato di [Come posso recuperare l'origine di una pagina Web?] (Http : //stackoverflow.com/questions/7800026/how-can-i-fetch-the-source-of-a-web-page) –

risposta

17

Utilizzando Indy:

const 
    HTTP_RESPONSE_OK = 200; 

function GetPage(aURL: string): string; 
var 
    Response: TStringStream; 
    HTTP: TIdHTTP; 
begin 
    Result := ''; 
    Response := TStringStream.Create(''); 
    try 
    HTTP := TIdHTTP.Create(nil); 
    try 
     HTTP.Get(aURL, Response); 
     if HTTP.ResponseCode = HTTP_RESPONSE_OK then begin 
     Result := Response.DataString; 
     end else begin 
     // TODO -cLogging: add some logging 
     end; 
    finally 
     HTTP.Free; 
    end; 
    finally 
    Response.Free; 
    end; 
end; 
+1

+1, in modo che la tua risposta sia al top! –

+0

@AndreasRejbrand: grazie :) –

+0

+1 MA, cosa mi serve in "usi" per ottenere su HTTP_RESPONSE_OK? – Mawg

14

Utilizzando il nativo di Microsoft Windows API WinInet:

function WebGetData(const UserAgent: string; const URL: string): string; 
var 
    hInet: HINTERNET; 
    hURL: HINTERNET; 
    Buffer: array[0..1023] of AnsiChar; 
    BufferLen: cardinal; 
begin 
    result := ''; 
    hInet := InternetOpen(PChar(UserAgent), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0); 
    if hInet = nil then RaiseLastOSError; 
    try 
    hURL := InternetOpenUrl(hInet, PChar(URL), nil, 0, 0, 0); 
    if hURL = nil then RaiseLastOSError; 
    try 
     repeat 
     if not InternetReadFile(hURL, @Buffer, SizeOf(Buffer), BufferLen) then 
      RaiseLastOSError; 
     result := result + UTF8Decode(Copy(Buffer, 1, BufferLen)) 
     until BufferLen = 0; 
    finally 
     InternetCloseHandle(hURL); 
    end; 
    finally 
    InternetCloseHandle(hInet); 
    end; 
end; 

Provalo:

procedure TForm1.Button1Click(Sender: TObject); 
begin 
    Memo1.Text := WebGetData('My Own Client', 'http://www.bbc.co.uk') 
end; 

Ma questo funziona solo se la codifica è UTF 8. Quindi, per farlo funzionare in altri casi, devi gestirli separatamente, oppure puoi usare i wrapper di alto livello di Indy, come suggerito da Marjan. Ammetto di essere superiore in questo caso, ma voglio comunque promuovere l'API sottostante, se non altro per motivi didattici ...

+0

+1 per l'utilizzo di materiale disponibile del sistema operativo. –

+0

LOL, mi dispiace, corretto. Il mio cervello sta diventando nebbioso. Deve essere perché ho passato 50 anni giovedì scorso. –

+0

+1 per "educational" :-) – Mawg

Problemi correlati