WEB SERVICE ayuda

WEB SERVICE ayuda

Postby eduare » Wed Nov 19, 2014 5:51 pm

Necesito ayuda con este tema
hay varias explicaciones y ejemplos en el foro pero
no logro entenderlos bien.
o me da errores o no hace nada.

Tengo que crear un CLIENTE y usarlo para acceder al servicio.

cualquier ayuda es muy bien recibida
gracias
eduare
 
Posts: 3
Joined: Wed Jul 02, 2014 8:05 pm

Re: WEB SERVICE ayuda

Postby Antonio Linares » Wed Nov 19, 2014 10:06 pm

Eduardo,

No tengo experiencia usando web services por lo que siento no poder ayudarte :-(

Seguro que aqui en estos foros habrá compañeros que puedan ayudarte :-)
regards, saludos

Antonio Linares
www.fivetechsoft.com
User avatar
Antonio Linares
Site Admin
 
Posts: 41314
Joined: Thu Oct 06, 2005 5:47 pm
Location: Spain

Re: WEB SERVICE ayuda

Postby Enrrique Vertiz » Thu Nov 20, 2014 5:49 am

Saludos, Yo recopile información y con la ayuda de Benjamin lo heche a andar, te explico como Yo lo entendo

1.- Primero creas el objeto de conexión

// Aperturando las funciones para WEBSERVICE en XHARBOUR - OBJETO HTTP
try
http:=createobject( "Microsoft.XMLHTTP")
catch
try
http:=createobject( "Microsoft.XMLHTTP")
catch
Alert("Error en la creacion del objeto Microsoft.XMLHTTP : " + Ole2TxtError())
return .F.
end
end

// Creando OBJETO XML
try
doc := CreateObject( "MSXML2.DOMDocument" )
catch
try
doc := CreateObject( "MSXML2.DOMDocument" )
catch
Alert("Error en la creacion del objeto MSXML2.DOMDocument : " + Ole2TxtError())
return .F.
end
end

2.- Luego creas el XML que vas a enviar con tu consulta
El contenido de este XML te lo debe facilitar el manual del servicio web que vas a invocar.

cxml:=""
cxml:=cxml+'<soapenv:Envelope xmlns:ser="http://service.sunat.gob.pe"'+chr(13)
cxml:=cxml+'xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"'+CHR(13)
cxml:=cxml+'xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">'+CHR(13)
cxml:=cxml+"<soapenv:Header>"
cxml:=cxml+" <wsse:Security>"
cxml:=cxml+" <wsse:UsernameToken>"
cxml:=cxml+" <wsse:Username>"+wfruc+cSolUsr+"</wsse:Username>"
cxml:=cxml+" <wsse:Password>"+cSolPwd+"</wsse:Password>"
cxml:=cxml+" </wsse:UsernameToken>"
cxml:=cxml+" </wsse:Security>"
cxml:=cxml+"</soapenv:Header>"
cxml:=cxml+"<soapenv:Body>"
cxml:=cxml+" <ser:getStatus>"
cxml:=cxml+" <ticket>"+cNud+"</ticket>"
cxml:=cxml+" </ser:getStatus>"
cxml:=cxml+"</soapenv:Body>"
cxml:=cxml+"</soapenv:Envelope>"


3.- Aquí llamas al URL donde se aloja el servicio Web y usas el método que necesitas

http:Open( "POST" , "https://www.sunat.gob.pe/ol-it-wsconscpegem/billConsultService" , .F. )
http:SetRequestHeader("Content-Type" ,"text/xml;charset=ISO-8859-1")
http:SetRequestHeader( "SOAPAction" , "getStatus" )


doc:LoadXML( cXml ) // Carga el documento a xml
IF doc:parseError:errorCode = 0
//"XML subio sin problemas"
ELSE
lcErrorMsg = "No fue posible cargar documento pues este no corresponde a su Schema"
lcErrorMsg = lcErrorMsg + " Linea: " + STR(xmldom:parseError:line)
lcErrorMsg = lcErrorMsg + " Caracter en linea: " + STR(xmldom:parseError:linepos)
lcErrorMsg = lcErrorMsg + " Causa del error: " + xmldom:parseError:reason+" Codigo: "+STR(xmldom:parseError:errorCode)
msginfo(lcErrorMsg)
ENDIF

TRY
http:send( doc:xml ) // Lo envio al WS
CATCH
cErrorMsg:="No Se Pudo Enviar Documento XML..."+CRLF+CRLF+"Sin Conexion a Internet o Servidor Con Problemas"
MsgInfo(cErrorMsg,"Intente Nuevamente")
return .f.
END

cTxtSun := http:responseText // Aquí tengo la respuesta del WS, la puedo manejar con la clase TXml o como un Texto con AT() o demás funciones.

Espero te sirva
Enrrique Vertiz Pitta
Lima-Peru
xHb 1.23.1026X, Fwh 23.04, MySQL 8.0.X, SQLLIB 1.9m, SQLRDD
Enrrique Vertiz
 
Posts: 514
Joined: Fri Oct 07, 2005 2:17 pm
Location: Lima - Peru

Re: WEB SERVICE ayuda

Postby eduare » Thu Nov 20, 2014 1:42 pm

Gracias a todos por responder Enrrique ,Benjamin,Antonio

Vamos a empezar ...
eduare
 
Posts: 3
Joined: Wed Jul 02, 2014 8:05 pm

Re: WEB SERVICE ayuda

Postby eduare » Mon Nov 24, 2014 8:05 pm

Enrrique

intenté cambiar este ejemplos por mis datos
y me dice "Diferente esquema"

con este ejemplo tal cual está
lógico que me dice que el USUARIO NO EXISTE
eduare
 
Posts: 3
Joined: Wed Jul 02, 2014 8:05 pm

Re: WEB SERVICE ayuda

Postby benjiben143 » Mon Nov 24, 2014 10:26 pm

Hola eduare

wenas tardes

si me puedes colocar lar liga a donde te quieres conectar , para echarle un vistazo y obtener la propiedades del mismo

me la puedes mandar también a chino72vale@hotmail.com


saludos
Benjamin Casarrubias Moreno
Cd. Obregon, Sonora, Mexico
chino72vale@hotmail.com
Fivewin 16.05, Harbour 3.2, xharbour 1.2.1, Fivelinux, visual estudio 2013
benjiben143
 
Posts: 114
Joined: Wed Mar 11, 2009 7:32 pm
Location: Obregon, Sonora, Mexico

Re: WEB SERVICE ayuda

Postby thefull » Tue Nov 25, 2014 9:04 am

Bueno, el webservices que quiere consumir tiene una pecualidad, y son 2;

1.- Importante, es tener en la cabecera ( "Connection:", "Keep-Alive" ) , de lo contrario, cuando establecemos conexión , esta es cerrada, dando un bonito valor nulo de respuesta.
2.- En la SOAPAction , hay que poner la URL entera, de lo contrario, el webservices devolverá que no existe la acción.
3.- usar soapUI, nos permite averiguar estos matices

Version MSXML2
Code: Select all  Expand view
function amigo_eduardo()
   Local cXml := strtran( memoread("EnvioCFE.xml"), hb_osnewline(), "" )
   Local cLocation := "http://190.64.89.202/SICFEServicesDINAPOLI/sicfe.svc"
   Local oHttp


   oHttp := CreateObject( "MSXML2.XMLHTTP" )

   oHttp:Open( "POST", cLocation, .F. )
   ohttp:SetRequestHeader("Content-Type" ,"text/xml;charset=UTF-8" )
   ohttp:SetRequestHeader( "SOAPAction" , "http://tempuri.org/ISICFEEmisor/EnvioCFE" )
   oHttp:SetRequestHeader( "Connection:", "Keep-Alive" )
   oHttp:SetRequestHeader( "Content-length: ", Str( len( cXml ) ) )
 
   oHttp:Send( cXml )
   Alert( oHttp:responseText   )

return nil
 


Version con CURL
Nota:
Enlaza estas librerias para CURL en tu makefile.
#SOPORTE PARA CURL
hbcurls.lib
libcurl.lib

Code: Select all  Expand view
#include "hbcurl.ch"
#include "common.ch"
#include "fileio.ch"

function amigo_eduardo_curl(  )

  local endpointUrl,curlHandle,curlErr
  local aHeader,chpmserv,cc1
   Local strXml := strtran( memoread("EnvioCFE.xml"), hb_osnewline(), "" )
   Local cLocation := "http://190.64.89.202/SICFEServicesDINAPOLI/sicfe.svc"

   cc1 := ""

   caction     := "EnvioCFE"
   endpointUrl := cLocation

   aHeader := {}
   AADD(aHeader,"Content-Type: text/xml;charset=UTF-8")
   AADD(aHeader,"SOAPAction: "+ cAction )
   AADD(aHeader,"Connection: Keep-Alive" )
   AADD(aHeader,"Content-length: "+ Str( len( strXml )) )

  curlHandle := curl_easy_init()

  if !empty(curlHandle)

      /* Specify the Header  data */
      curl_easy_setopt(curlHandle,HB_CURLOPT_HTTPHEADER,aHeader)

      /* Set the endpoint to send the POST to */
      curl_easy_setopt(curlHandle, HB_CURLOPT_URL, endpointUrl)

      /* Setup response data */
      curl_easy_setopt( curlHandle, HB_CURLOPT_DOWNLOAD )
      curl_easy_setopt( curlHandle, HB_CURLOPT_DL_BUFF_SETUP )

      /* Specify the POST data */
      curl_easy_setopt(curlHandle, HB_CURLOPT_POST, 1)
      curl_easy_setopt(curlHandle, HB_CURLOPT_POSTFIELDS, strxml)

      /* Do everything */
       curlErr := curl_easy_perform( curlHandle )

      /* Report any errors */
      if empty(curlErr)
         /* store response in variable */
         cc1 := curl_easy_dl_buff_get( curlHandle )
         Alert( "ATENCION:" +  strtran( htmltoansi( cc1 ), "&quot;", '"' ) )
      else
         Alert(  "Error:" + curl_easy_strerror(curlErr) )
      endif
  else
      Alert(  "No handle" )
  endif

  if !empty(curlHandle)
     /* Clean-up libcurl */
     curl_global_cleanup( curlHandle )
  else
     Alert(  "Error" )
  endif

  if empty(cc1)
     Alert(  "Error" )
  endif
return cc1
 
Saludos
Rafa Carmona ( rafa.thefullARROBAgmail.com___quitalineas__)
User avatar
thefull
 
Posts: 729
Joined: Fri Oct 07, 2005 7:42 am
Location: Barcelona

Re: WEB SERVICE ayuda

Postby thefull » Tue Nov 25, 2014 10:33 am

Buenas

Una tercera solución es usar el cliente de Soap.
Aqui teneis el mismo ejemplo, os lo pongo en Harbour y el VBS para que si necesitais ayuda/documentación, os podeis basar en VBS para obtener la ayuda;

Code: Select all  Expand view
function amigo_eduardo_soap()
   Local cValue := ""
   Local oSoapClient
   Local lOk, orespuesta, i
   Local cDominio_WebServices := "http://190.64.89.202/SICFEServicesDINAPOLI/sicfe.svc?singleWsdl"
   Local item, objSub
   
   lOk := .T.
   oSoapClient := NIL
   

        oSoapClient  := CreateObject( "MSSOAP.SoapClient30" )  // Conecta a SOAP 3.0
        oSoapClient:msSoapInit( cDominio_WebServices )
   
         try
         orespuesta := oSoapClient:EnvioCFE("erp", "erp", "dinapo", "", "cfe", "123", "", .t., 32, 0, "", "", .t., .t., "1.33")  
         item :=  oRespuesta:context
          For Each objSub In item:childNodes
              Alert(  "Nombre nodo:" + objSub:nodeName  + ( if( !emptY( objSub:text ), " Valor:" + objSub:text,"" ) ) )
             If objSub:Attributes:length > 0
                For i = 0 To objSub:Attributes:length - 1
                    Alert(  "Atributo:" +objSub:Attributes(i):nodeName + " - " + objSub:Attributes(i):nodeValue )
                Next
             End If
          next          
         catch
            cValue := oSOAPClient:faultString + Hb_OsNewLine() + oSOAPClient:detail
            alert( "error:"+cValue )
         end

   oSoapClient := NIL

return nil


Version VBS que os puede servir para buscar info sobre ello;

Code: Select all  Expand view
 Set oSoapClient = CreateObject( "MSSOAP.SoapClient30" )
  oSoapClient.msSoapInit( "http://190.64.89.202/SICFEServicesDINAPOLI/sicfe.svc?singleWsdl" )
 
  Set o = oSoapClient.EnvioCFE( "erp", "erp", "dinapo", "", "cfe", "123", "", True, 32, 0, "", "", True, True, "1.33" ) 
  Set item = o.context
 
  WScript.Echo TypeName( o )
 
  For Each objSub In item.childNodes
        WScript.Echo "Nombre nodo:" & objSub.nodeName & " Valor:" & objSub.text
       
        If objSub.Attributes.length > 0 Then
            For i = 0 To objSub.Attributes.length - 1
                WScript.Echo objSub.Attributes(i).nodeName & " - " & objSub.Attributes(i).nodeValue
            Next
        End If

    Next
 


Creo que por mi parte, he dejado la puerta a que podais comprender un poco mas esto de los webservices.
Todo ejemplo aqui publicado espero os ilumine ;-)

Saludos Cordiales
Saludos
Rafa Carmona ( rafa.thefullARROBAgmail.com___quitalineas__)
User avatar
thefull
 
Posts: 729
Joined: Fri Oct 07, 2005 7:42 am
Location: Barcelona

Re: WEB SERVICE ayuda

Postby jose_murugosa » Tue Nov 25, 2014 3:25 pm

Hola,
Gracias por los ejemplos!!

Es de lo más claro que he visto en los foros sobre Web Services, justo lo que necesito!!!!!!!, Muuuuchas Gracias.

Me pondré a hacer pruebas :)

Espero poder compartir experiencia de exito al respecto :) y si no.... me tendrán haciendo alguna preguntilla....
Saludos/Regards,
José Murugosa
FWH + Harbour + Bcc7. Una seda!
User avatar
jose_murugosa
 
Posts: 1144
Joined: Mon Feb 06, 2006 4:28 pm
Location: Uruguay


Return to FiveWin para Harbour/xHarbour

Who is online

Users browsing this forum: No registered users and 97 guests