HTTP Get (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This code shows hot to make HTTP GET requests to get wiki pages. You can change the server address (http://en.wikipedia.org) or the page name (Main Page) to get different results.

Code

program HTTPGet;

{$APPTYPE CONSOLE}
{$R *.res}

uses
  SysUtils, HTTPApp, IdHTTP, XMLDoc, XMLIntf, ActiveX;

const
  ServerAddress = 'http://en.wikipedia.org';

var
  CoResult: Integer;
  HTTP: TIdHTTP;
  Query: String;
  Buffer: String;
  Doc: IXMLDocument;
  Node: IXMLNode;

begin
  try
    CoResult := CoInitializeEx(nil, COINIT_MULTITHREADED);

    if not((CoResult = S_OK) or (CoResult = S_FALSE)) then
    begin
      Writeln('Failed to initialize COM library.');
      Exit;
    end;
    HTTP := TIdHTTP.Create;

    // Build query
    // For more information, see http://www.mediawiki.org/wiki/API:Query
    Query := ServerAddress + '/w' + '/api.php?' +
      'action=query&prop=revisions&rvprop=content&format=xml&titles=' +
      String(HTTPEncode('Main Page'));

    // HTTP GET request
    Buffer := HTTP.Get(Query);

    // Create XML document
    Doc := TXMLDocument.Create(nil);

    // Build XML document from HTTP response
    Doc.LoadFromXML(Buffer);

    // Display document content
    Writeln(Doc.XML.Text);

    // Get main node
    Node := Doc.ChildNodes.FindNode('api');

    // Process XML data
    // ...

    HTTP.Destroy;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;

end.

Uses

See Also