Não é a linguagem de programação que define o programador, mas sim sua lógica

Consultando CEP utilizando componente IdHTTP


Então pessoal vamos construir uma aplicação de consulta de CEP utilizando o IdHTTP de uma maneira bem simples, trabalhando com WebServices

Vamos utilizar:


Ficara semelhante a...

Criaremos  duas classes em um mesma Unit
Nas Uses colocar Classes, SysUtils, IdHTTP, XMLDoc
unit UConsultarCEP;

interface

uses Classes, SysUtils, IdHTTP, XMLDoc, Dialogs, StrUtils;

type
  TCep = packed record
    Logradouro: String;
    Bairro: String;
    Cidade: String;
    Uf: String;
    Resultado: String;
  end;

  TConsultarCEP = class(TComponent)
  private
    FHttp: TIdHTTP;
    FXml: TXMLDocument;
  public
    constructor Create(AOwner: TComponent; AKey: String = '');
    function Search(const aCep: String): TCep;
  end;

implementation

{ TConsultaCep }

constructor TConsultarCEP.Create(AOwner: TComponent; AKey: String);
begin
  inherited Create(AOwner);
  Self.FHttp := TIdHTTP.Create(Self);
  Self.FXml := TXMLDocument.Create(Self);
  Self.FXml.Active := True;
end;

function TConsultarCEP.Search(const aCep: String): TCep;
var
  lResultado: String;
  lTipoLogradouro: String;
begin
  try
    lResultado := Self.FHttp.Get('http://republicavirtual.com.br/web_cep.php?cep=' + aCep);
    Self.FXml.LoadFromXML(lResultado);
    if Self.FXml.DocumentElement.ChildValues['resultado'] = 0 then
      ShowMessage(Self.FXml.DocumentElement.ChildValues['resultado_txt'])
    else begin
      if not(Self.FXml.DocumentElement.ChildValues['resultado'] = 2) then begin
        lTipoLogradouro := Self.FXml.DocumentElement.ChildValues['tipo_logradouro'];
        Result.Logradouro := lTipoLogradouro +
          IfThen(lTipoLogradouro <> EmptyStr, ': ') +
          Self.FXml.DocumentElement.ChildValues['logradouro'];
        Result.Bairro := Self.FXml.DocumentElement.ChildValues['bairro'];
      end;
      Result.Cidade := Self.FXml.DocumentElement.ChildValues['cidade'];
      Result.Uf := Self.FXml.DocumentElement.ChildValues['uf'];
      Result.Resultado := Self.FXml.DocumentElement.ChildValues['resultado_txt'];
    end;
  finally
    Self.FHttp.Free;
    Self.FXml.Free;
  end;
end;

end.

No evento de OnClick do TButton coloque o seguinte
procedure TFCEP.BtnPesquisarClick(Sender: TObject);
var
  lCep: TCep;
begin
  lCep := TConsultarCEP.Create(Self).Search(edCEP.Text);
  mmResultados.Clear;
  mmResultados.Lines.Add('Resultado: ' + lCep.Resultado);
  mmResultados.Lines.Add('');
  mmResultados.Lines.Add('Logradouro: ' + lCep.Logradouro);
  mmResultados.Lines.Add('Bairro: ' + lCep.Bairro);
  mmResultados.Lines.Add('Cidade: ' + lCep.Cidade);
  mmResultados.Lines.Add('UF: ' + lCep.Uf);
end;


0 comentários:

Postar um comentário