Jump to content
Fivewin Brasil

Busca de Dados via cURL GET


betovsp

Recommended Posts

Olá Pessoal.

Preciso de ajuda no seguinte.

O Site Cosmos libera consulta de NCM entre outros dos produtos, e pode fazer a busca através da api deles da seguinte forma:

  1. curl -i -X GET \
  2. -H "Content-Type:application/json" \
  3. -H "X-Cosmos-Token:yIgeHB34Qv6RO18QWsftQw" \
  4. 'https://api.cosmos.bluesoft.com.br/gtins/7891910000197.json'

Me ajudem a passar essa busca em fivewin por favor.

Obrigado.

Beto.

Link to comment
Share on other sites

  • 2 weeks later...
Veja se serve para Você


FUNCTION BuscaCosmos( cCodi )

LOCAL hCurl

LOCAL cUrlc := "https://api.cosmos.bluesoft.com.br/gtins/"+ allTrim( cCodi ) + ".json"

LOCAL cRetu := ""


curl_global_init()

IF !empty( hCurl := curl_easy_init() )

curl_easy_setopt( hCurl, HB_CURLOPT_HTTPHEADER, {"Content-Type:application/json","X-Cosmos-Token:yIgeHB34Qv6RO18QWsftQw"} )

curl_easy_setopt( hCurl, HB_CURLOPT_URL, cUrlc )

curl_easy_setopt( hCurl, HB_CURLOPT_SSL_VERIFYPEER, .F. )

curl_easy_setopt( hCurl, HB_CURLOPT_TRANSFERTEXT, .T. )

curl_easy_setopt( hCurl, HB_CURLOPT_FAILONERROR, .T. )

curl_easy_setopt( hCurl, HB_CURLOPT_DL_BUFF_SETUP )

curl_easy_perform( hCurl )

cRetu := curl_easy_dl_buff_get( hCurl )

curl_easy_reset( hCurl )

ENDIF

curl_global_cleanup()

RETURN cRetu

Link to comment
Share on other sites

uso MS-VC e um harbour made in casa. Meu bat para compilar e:

SET INCLUDE=D:\MSVS10\include;D:\MSVS10\SDK\v7.0A\Include
SET LIB=D:\MSVS10\SDK\v7.0A\Lib;D:\MSVS10\Lib
SET PATH=D:\MSVS10\bin;D:\MSVS10\SDK\v7.0A\bin;D:\harbourgit\bin\win\msvc;D:\MSVS10\Common7\IDE;C:\WINDOWS;C:\WINDOWS\SYSTEM32
hbmk2 -ldflag=/FORCE:MULTIPLE -ldflag=/NODEFAULTLIB:msvcrt -iD:\fwh1507\include -iINCLUDE TEST.hbm D:\FWH1507\fwhc32.hbc D:\harbourgit\contrib\hbcurl\hbcurl.hbc
Meu fwhc32.hbc é:
{win}gt=gtgui
{win}libs=KERNEL32 USER32 GDI32 WINSPOOL COMCTL32 COMDLG32 ADVAPI32 SHELL32 OLE32 OLEAUT32 UUID ODBC32 ODBCCP32 IPHLPAPI MPR VERSION WSOCK32 MSIMG32 OLEDLG PSAPI GDIPLUS WINMM
{win}libs=HBWIN HBCT HBMEMIO PNG HBTIP XHB HBMZIP HBZIPARC MINIZIP
libpaths=D:\FWH1507\LIB
libs=FIVEHC32 FIVEH32 DOLPHINVC LIBMYSQLM
acho que só precisei acrescentar o hbcurl para funcionar.
Link to comment
Share on other sites

pois é, eu utilizo bcc + xharbour / Harbour, mas nem com um nem com o outro o trem funciona, precisa dessa lib, achei no xharbour, mas dá o mesmo erro....precisa ler a lib do xharbour para saber o nome das funções, se é que são diferentes....mas continuando a saga... vlw por enquanto o que vc puder me ajudar eu agradeço.

Link to comment
Share on other sites

  • 8 months later...

Boa tarde amigos!

Consegui fazer funcionar esta pesquisa, se for de interesse de alguém...

**************************************

Function PesquisaNCM()


    * pesquisa NCM via API Cosmos : https://cosmos.bluesoft.com.br
    local oHttp, cUrl, aResult
    local cGTIN:= Space(13)
    
    MsgGet("Pesquisa NCM Cosmos", "Informe o código GTIN", @cGTIN)
    
    if Empty(cGTIN)
        return nil
    endif
        
    cUrl:= "https://api.cosmos.bluesoft.com.br/gtins/"+ cGTIN + ".json"
    
    oHttp:= CreateObject( 'MSXML2.ServerXMLHTTP.6.0' )
                             
    oHttp:Open( "GET", cUrl, .f. )
   oHttp:setRequestHeader('Content-Type'  , 'application/json')             
   oHttp:setRequestHeader('X-Cosmos-Token', 'yIgeHB34Qv6RO18QWsftQw')             

    oHttp:Send()

    IF oHttp:status != 200
        MsgStop( Alltrim(Str(oHttp:status)) +" - "+ oHttp:statusText , "Erro na requisição")
        RETURN NIL
    ENDIF    

    x :=  hb_jsondecode( oHttp:ResponseBody, @aResult )

    xbrowse(aResult, "Resultado")
    
return nil

Link to comment
Share on other sites

 

Boa tarde amigos!

Consegui fazer funcionar esta pesquisa, se for de interesse de alguém...

**************************************

Function PesquisaNCM()


    * pesquisa NCM via API Cosmos : https://cosmos.bluesoft.com.br
    local oHttp, cUrl, aResult
    local cGTIN:= Space(13)
    
    MsgGet("Pesquisa NCM Cosmos", "Informe o código GTIN", @cGTIN)
    
    if Empty(cGTIN)
        return nil
    endif
        
    cUrl:= "https://api.cosmos.bluesoft.com.br/gtins/"+ cGTIN + ".json"
    
    oHttp:= CreateObject( 'MSXML2.ServerXMLHTTP.6.0' )
                             
    oHttp:Open( "GET", cUrl, .f. )
   oHttp:setRequestHeader('Content-Type'  , 'application/json')             
   oHttp:setRequestHeader('X-Cosmos-Token', 'yIgeHB34Qv6RO18QWsftQw')             

    oHttp:Send()

    IF oHttp:status != 200
        MsgStop( Alltrim(Str(oHttp:status)) +" - "+ oHttp:statusText , "Erro na requisição")
        RETURN NIL
    ENDIF    

    x :=  hb_jsondecode( oHttp:ResponseBody, @aResult )

    xbrowse(aResult, "Resultado")
    
return nil

Edí

 

Boa noite

 

Vc compilou com xHb? Usou alguma LIB e/ou .CH específico? Caso sim nas duas questões, pode disponibilizar?

 

[]s, 

 

 

Link to comment
Share on other sites

* Função para obter NCM do site da Receita Federal

function BuscaNCM( _NCM, _oDlg )
   LOCAL cHtml := "", nLeng := LEN(ALLTRIM( ClearChar(_NCM, {"."}) )), lNCMOk := .F.
   if empty(_NCM) ; return .F. ; endif
   IF nLeng < 8 .AND. nLeng > 0
      SysRefresh() ; MsgAlert("O código do NCM deve conter 8 Caracteres","Aviso")
      RETURN .F.
   ENDIF
   url := "http://www4.receita.fazenda.gov.br/simulador/PesquisarNCM.jsp?codigo="+LEFT(_NCM,2)+"&codigoCapitulo="+LEFT(_NCM,2)+"&codigoPosicao=&button=Exibir+NCMs"
   try
		oUrl:=TUrl():New( url ) // From tip.lib
		oHttp := TipClientHttp():New( oUrl , .f. ) // From tip.lib
   catch
      SysRefresh() ; MsgAlert("Erro ao tentar criar o objeto Http","Aviso")
   	return .f.
   end try

	Try
		oHttp:Open()
		cHtml := oHttp:ReadAll() // Baixa todo o conteúdo do site.
	Catch oErr
      SysRefresh() ; MsgAlert("Erro ao tentar conectar o objeto Http","Aviso")
		RETURN .f.
	End
	oHttp:Close()
	DeleteUrlCacheEntry(url) // Lipar Cache

   IF Empty(cHtml)
      SysRefresh() ; MsgAlert("Conteúdo vazio","Aviso")
      RETURN .F.
   ENDIF

   cHtml := "["+UnicodeToStr(cHtml, .t.)+"]"
   
   IF "codNCM.value='"+_NCM+"'" $ cHtml
      MsgInfo("NCM válido","Ok")      
      lNCMOk := .T.
   ELSE
      MsgAlert("NCM inválido","Aviso")      
   ENDIF
   
	if _oDlg <> nil ; _oDlg:Update() ; endif
RETURN(lNCMOk)

 

Link to comment
Share on other sites

 

Edí

 

Boa noite

 

Vc compilou com xHb? Usou alguma LIB e/ou .CH específico? Caso sim nas duas questões, pode disponibilizar?

 

[]s, 

 

 

Bom dia!

Nada específico. Compilei com Fwh1109, xHarbour 1.2.3 e bcc 5.8.2. 

Abraço.

Link to comment
Share on other sites

 

* Função para obter NCM do site da Receita Federal

function BuscaNCM( _NCM, _oDlg )
   LOCAL cHtml := "", nLeng := LEN(ALLTRIM( ClearChar(_NCM, {"."}) )), lNCMOk := .F.
   if empty(_NCM) ; return .F. ; endif
   IF nLeng < 8 .AND. nLeng > 0
      SysRefresh() ; MsgAlert("O código do NCM deve conter 8 Caracteres","Aviso")
      RETURN .F.
   ENDIF
   url := "http://www4.receita.fazenda.gov.br/simulador/PesquisarNCM.jsp?codigo="+LEFT(_NCM,2)+"&codigoCapitulo="+LEFT(_NCM,2)+"&codigoPosicao=&button=Exibir+NCMs"
   try
		oUrl:=TUrl():New( url ) // From tip.lib
		oHttp := TipClientHttp():New( oUrl , .f. ) // From tip.lib
   catch
      SysRefresh() ; MsgAlert("Erro ao tentar criar o objeto Http","Aviso")
   	return .f.
   end try

	Try
		oHttp:Open()
		cHtml := oHttp:ReadAll() // Baixa todo o conteúdo do site.
	Catch oErr
      SysRefresh() ; MsgAlert("Erro ao tentar conectar o objeto Http","Aviso")
		RETURN .f.
	End
	oHttp:Close()
	DeleteUrlCacheEntry(url) // Lipar Cache

   IF Empty(cHtml)
      SysRefresh() ; MsgAlert("Conteúdo vazio","Aviso")
      RETURN .F.
   ENDIF

   cHtml := "["+UnicodeToStr(cHtml, .t.)+"]"
   
   IF "codNCM.value='"+_NCM+"'" $ cHtml
      MsgInfo("NCM válido","Ok")      
      lNCMOk := .T.
   ELSE
      MsgAlert("NCM inválido","Aviso")      
   ENDIF
   
	if _oDlg <> nil ; _oDlg:Update() ; endif
RETURN(lNCMOk)

 

No seu exemplo falta vc mostrar as functions

DeleteUrlCacheEntry() e a +UnicodeToStr()

Link to comment
Share on other sites

//----------------------------------------------------------------------------------------------------------------------//
DLL Function DeleteUrlCacheEntry(lpszUrlName AS STRING) AS LONG PASCAL FROM "DeleteUrlCacheEntryA" LIB "wininet.dll"
//----------------------------------------------------------------------------------------------------------------------//
Link to comment
Share on other sites

 

//----------------------------------------------------------------------------------------------------------------------//
DLL Function DeleteUrlCacheEntry(lpszUrlName AS STRING) AS LONG PASCAL FROM "DeleteUrlCacheEntryA" LIB "wininet.dll"
//----------------------------------------------------------------------------------------------------------------------//

Ainda falta uma  -->> UnicodeToStr()

Link to comment
Share on other sites

FUNCTION UnicodeToStr(_cStr, lTiraAcento)
   LOCAL _cNewStr := _cStr
   LOCAL aConvert := {}
   AADD(aConvert, {"á", "\u00e1"})
   AADD(aConvert, {"à", "\u00e0"})
   AADD(aConvert, {"â", "\u00e2"})
   AADD(aConvert, {"ã", "\u00e3"})
   AADD(aConvert, {"ä", "\u00e4"})
   AADD(aConvert, {"Á", "\u00c1"})
   AADD(aConvert, {"À", "\u00c0"})
   AADD(aConvert, {"Â", "\u00c2"})
   AADD(aConvert, {"Ã", "\u00c3"})
   AADD(aConvert, {"Ä", "\u00c4"})
   AADD(aConvert, {"é", "\u00e9"})
   AADD(aConvert, {"è", "\u00e8"})
   AADD(aConvert, {"ê", "\u00ea"})
   AADD(aConvert, {"ê", "\u00ea"})
   AADD(aConvert, {"É", "\u00c9"})
   AADD(aConvert, {"È", "\u00c8"})
   AADD(aConvert, {"Ê", "\u00ca"})
   AADD(aConvert, {"Ë", "\u00cb"})
   AADD(aConvert, {"í", "\u00ed"})
   AADD(aConvert, {"ì", "\u00ec"})
   AADD(aConvert, {"î", "\u00ee"})
   AADD(aConvert, {"ï", "\u00ef"})
   AADD(aConvert, {"Í", "\u00cd"})
   AADD(aConvert, {"Ì", "\u00cc"})
   AADD(aConvert, {"Î", "\u00ce"})
   AADD(aConvert, {"Ï", "\u00cf"})
   AADD(aConvert, {"ó", "\u00f3"})
   AADD(aConvert, {"ò", "\u00f2"})
   AADD(aConvert, {"ô", "\u00f4"})
   AADD(aConvert, {"õ", "\u00f5"})
   AADD(aConvert, {"ö", "\u00f6"})
   AADD(aConvert, {"Ó", "\u00d3"})
   AADD(aConvert, {"Ò", "\u00d2"})
   AADD(aConvert, {"Ô", "\u00d4"})
   AADD(aConvert, {"Õ", "\u00d5"})
   AADD(aConvert, {"Ö", "\u00d6"})
   AADD(aConvert, {"ú", "\u00fa"})
   AADD(aConvert, {"ù", "\u00f9"})
   AADD(aConvert, {"û", "\u00fb"})
   AADD(aConvert, {"ü", "\u00fc"})
   AADD(aConvert, {"Ú", "\u00da"})
   AADD(aConvert, {"Ù", "\u00d9"})
   AADD(aConvert, {"Û", "\u00db"})
   AADD(aConvert, {"ç", "\u00e7"})
   AADD(aConvert, {"Ç", "\u00c7"})
   AADD(aConvert, {"ñ", "\u00f1"})
   AADD(aConvert, {"Ñ", "\u00d1"})
   AADD(aConvert, {"&", "\u0026"})
   AADD(aConvert, {"'", "\u0027"})
   FOR nX := 1 TO LEN(aConvert)
      IF aConvert[nX,2] $ _cNewStr
         _cNewStr := STRTRAN(_cNewStr, aConvert[nX,2], aConvert[nX,1])
      ENDIF
   NEXT
RETURN(IIF(lTiraAcento,TiraAcentos(_cNewStr),_cNewStr))
*------------------------------------------------------------------------------------------------
FUNCTION TiraAcentos(cStr)
   LOCAL cStrNew := "", nX, aAcento, aLetras
   aAcento := {"Æ","Â"," ","µ","…","·","‚","","ˆ","Ò","¡","Ö","¢","à","ä","å","“","â","£","é","","š","ã","Ã","á","Á","à","À","é","É","ê","Ê","í","Í","ó","Ó","õ","Õ","ô","Ô","ú","Ú","ü","Ü","ù","ç","‡","Ç","€","§","¦","º","°","ª"}
   aLetras := {"a","A","a","A","a","A","e","E","e","E","i","I","o","O","o","O","o","O","u","U","u","U","a","A","a","A","a","A","e","E","e","E","i","I","o","O","o","O","o","O","u","U","u","U"," ","c","c","C","C",".",".",".",".","."}
   FOR nX := 1 TO LEN(aAcento)
       cStrNew := STRTRAN(cStr,aAcento[nX],aLetras[nX])
       cStr := cStrNew
   NEXT
   IF EMPTY(cStrNew)
   	cStrNew := cStr
   ENDIF
RETURN(cStrNew)
*------------------------------------------------------------------------------------------------

 

Link to comment
Share on other sites

  • 2 years later...

Não está dando certo.

O código que sempre usei é esse:

*********************************************
Function BuscaNCM( cNumNCM, cDesNCM ) // Pega a Descrição da NCM na Internet //
*********************************************
   Local   oPg, i
   Default cDesNCM := "OUTROS"
   cNumNCM := Alltrim(StrNum(cNumNCM,.F.))
   cBuf    := ""
   if isinternet()
      if !empty(cNumNCM)
         oPg:=CreateObject("Microsoft.XMLHTTP")
       //oPg:Open("GET","http://www4.receita.fazenda.gov.br/simulador/PesquisarNCM.jsp?codigo="+left(cNumNCM,4),.F.)
       //Exemplo: http://www4.receita.fazenda.gov.br/simulador/PesquisarNCM.jsp?codigo=732599&codigoCapitulo=73&codigoPosicao=7325&codigoSubPosicao1=73259&codigoSubPosicao2=732599#
         oPg:Open("GET","http://www4.receita.fazenda.gov.br/simulador/PesquisarNCM2.jsp?codigo="+left(cNumNCM,6)+;
                                                                              "&codigoCapitulo="+left(cNumNCM,2)+;
                                                                               "&codigoPosicao="+left(cNumNCM,4)+;
                                                                           "&codigoSubPosicao1="+left(cNumNCM,5)+;
                                                                           "&codigoSubPosicao2="+left(cNumNCM,6)+;
                                                                           "&button=Exibir+NCMs",.F.)
         ErroNET:=.f.
         Try
            oPg:Send()
            catch oError
            ErroNET:=.T.
         End Try
         if !ErroNET
            cBuf := oPg:responseBody
         end
      end
   end
   if !Empty(cBuf)
      xPOS1 := at('<div id="listaNCM">',cBUF)
      xPOS2 := at('</div>',cBUF)
      cBUF  := subs(cBUF,xPOS1,xPOS2-xPOS1)
      xPOSN := at(cNumNCM,cBUF)
      if xPOSN # 0
         cBUF    := right(cBUF,len(cBUF)-(xPOSN+21))
         for i=1 to Len(cBuf)
            if Subst(cBuf,i,1)$" -"
               Loop
            endif
            cBuf:=Subst(cBuf,i,Len(cBuf))
            Exit
         next
         xPOSF   := at('</a> </font>',cBUF)
         cDesNCM := left(cBUF,xPOSF-1)
      end
   end
   cDesNCM := iif(Empty(cDesNCM), "OUTROS", cDesNCM)
Return( cDesNCM )

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...