APIs e Microsserviços

8 nov, 2007

WebServices em ASP Classico

Publicidade

Olá Developers.

Atualmente todo mundo procura utilizar webservices, é uma tecnologia fantástico, mas por maior que sejam os esforços das comunidades, ainda existe uma grande dificuldade de como acessar webservices com tecnologia obsoletas como ASP Classico, VB6 e outras tantas que podem até estar na crista da onda ainda, mas no fundo não oferencem o suporte adequado à webservices como Delphi.

Após inúmeros pedidos de clientes que tentam realizar integrações de webservices e sofrem por não ter uma solução prática para implementar o mesmo, resolvi fazer um exemplo e não é HelloWorld()!

Basicamente nosso exemplo é feito em ASP Clássico com uma CLASS de apoio para se livrar de uso externo de componentes como Microsoft SOAP Client, que nem sempre está disponível em um Shared Host.

Criar um arquivo cls_webservices.asp

<code>
&lt;%
'***********************************************************************************
'
' Classe para acessar WebServices
' Author: Angelo Bestetti
' http://www.i-stream.com.br
' Purpose: Acessar webservices www.consultacpf.com
' Date: 2007/10/18
'***********************************************************************************
Option Explicit


'**************************************************** 
' Classe para WebService
'****************************************************

Class WebService
  Public Url
  Public Method
  Public Response
  Public Parameters
 
  ' Funcao para Invokar o WebService
  Public Function Invoke()
    Dim xmlhttp
    Set xmlhttp = Server.CreateObject("MSXML2.XMLHTTP")
    xmlhttp.open "POST", Url & "/" & Method, false
    xmlhttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
    xmlhttp.Send Parameters.toString
    response = xmlhttp.responseText
    set xmlhttp = nothing
  End Function
  
  
  Private Sub Class_Initialize()
    Set Parameters = New wsParameters
  End Sub
  
  Private Sub Class_Terminate()
    Set Parameters = Nothing
  End Sub
  
End class

'**************************************************** 
' Classe para wsParameters
'****************************************************
Class wsParameters
  Public mCol
  Public Function toString()
    Dim nItem
    Dim buffer
    buffer = ""
    For nItem = 1 to Count
      buffer = buffer & Item(nItem).toString & "&"
    Next
    If right(buffer,1)="&" then
      buffer = left(buffer,len(buffer)-1)
    End if
    toString = buffer 
  End Function
  
  Public Sub Clear
    set mcol = nothing 
    Set mCol = Server.CreateObject("Scripting.Dictionary") 
  End Sub
  
  Public Sub Add(pKey,pValue)
    Dim NewParameter
  
    Set NewParameter = New wsParameter
    NewParameter.Key = pKey
    NewParameter.Value = pValue
    mCol.Add mCol.count+1, NewParameter
  
    Set NewParameter = Nothing
  End Sub
  
  Public Function Item(nKey)
    Set Item=mCol.Item(nKey)
  End Function
  
  Public Function ExistsXKey(pKey)
    Dim nItem
  
    For nItem = 1 to mcol.count
      If mCol.Item(nItem).key = pKey Then
        ExistsXKeyword = True
        Exit For
      End if
    Next
  End Function
  
  Public Sub Remove(nKey)
    mCol.Remove(nKey)
  End sub
  
  Public Function Count()
    Count=mCol.count
  End Function
  
  Private Sub Class_Initialize()
    Set mCol = Server.CreateObject("Scripting.Dictionary")
  End Sub
  
  Private Sub Class_Terminate()
    Set mCol = Nothing
  End Sub
  
End class

'**************************************************** 
' Classe para wsParameter
'****************************************************
Class wsParameter
   Public Key
   Public Value
   Public Function toString()
     toString = Key & "=" & Value
   End Function
End Class
%&gt;

</code>

Criar um arquivo onde voce vai fazer sua consulta, o exemplo abaixo realiza uma consulta de exemplo no www.consultacpf.com

<code>
&lt;!--#include file="cls_webservice.asp"--&gt;
&lt;%
    dim ws
 
    set ws = new webservice
    ws.url = "http://www.consultacpf.com/webservices/consultacpf.asmx"
	' Podendo ser: ConsultaSaldoCliente, ConsultaSinteseCadastralSERASA, ConsultaSimplesSERASASandBox, ConsultaSimplesSERASA, ConsultaDetalhadaSERASA
	' Maiores Informações: http://www.consultacpf.com/webservices/consultacpf.asmx
    ws.method = "ConsultaDetalhadaSERASA" 

    ws.parameters.Add "Email","seuemailaqui"
    ws.parameters.Add "Senha","suasenhaaqui"
    ws.parameters.Add "Documento","cpf/cnpj a ser consultado"
 
    ws.Invoke
    response.Write ws.response

    set ws = nothing
%&gt;
</code>

Este exemplo mostra como é facil chamar um webservice e receber um XML de retorno. Claro que você pode adaptar este código para fazer consultas em outro webservice qualquer. Esta é a ideia.

Este exemplo está disponivel para download no endereço abaixo:

http://dn.consultacpf.com/files/folders/asp_30_classico/default.aspx

That´s all folks