1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

  2. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

Integração Datasul X E-millennium via API OData/REST

Discussão em 'EMS , HCM e Totvs 11' iniciado por Neivaldo, Janeiro 30, 2020.

  1. Neivaldo

    Neivaldo Membro Participativo

    Boa tarde Anderson,

    Foi algo parecido que fizemos, e já estamos conseguindo fazer a requisição.

    Agora estou tentando enviar os parâmetros necessários e verificar se tenho o retorno via .json.

    Há algum método especifico para envio dos parâmetros? Estou adicionando na variável "oUri:path .

    Quando enviamos sem informar os parâmetros "?data_atualizacao=2020-02-04-11-40..." não ocorre erro.

    /** This is free and unencumbered software released into the public domain.
    Anyone is free to copy, modify, publish, use, compile, sell, or
    distribute this software, either in source code form or as a compiled
    binary, for any purpose, commercial or non-commercial, and by any
    means. **/
    /*------------------------------------------------------------------------
    File : get_applications.p
    Purpose : Returns the list of applications from a PASOE server
    Author(s) : pjudge
    Created : Thu Oct 13 09:17:32 EDT 2016
    Notes : * this is the equivalent of curl -X GET -v http://localhost:16680/oemanager/applications/ -u tomcat:tomcat
    ----------------------------------------------------------------------*/
    block-level on error undo, throw.

    using OpenEdge.Net.HTTP.ClientBuilder.
    using OpenEdge.Net.HTTP.Credentials.
    using OpenEdge.Net.HTTP.IHttpClient.
    using OpenEdge.Net.HTTP.IHttpRequest.
    using OpenEdge.Net.HTTP.RequestBuilder.
    using OpenEdge.Net.URI.
    using OpenEdge.Net.HTTP.IHttpResponse.
    using Progress.Json.ObjectModel.JsonObject.
    using Progress.Json.ObjectModel.JsonArray.

    /* *************************** Session config *************************** */
    /* OPTIONAL FOR DEBUG/TRACING
    session:error-stack-trace = true.
    log-manager:logging-level = 6.
    log-manager:logfile-name = session:temp-dir + 'get_applications.log'.
    log-manager:clear-log().
    */

    /* *************************** Main Block *************************** */
    define variable oClient as IHttpClient no-undo.
    define variable oUri as URI no-undo.
    define variable oReq as IHttpRequest no-undo.
    define variable oResp as IHttpResponse no-undo.
    define variable oCreds as Credentials no-undo.
    define variable oJson as JsonObject no-undo.
    def var oJsonRespObj as JsonObject no-undo.
    def var oJsonRespArray as JsonArray no-undo.
    def var oJsonObj as JsonObject no-undo.
    def var oJsonArray as JsonArray no-undo.



    def temp-table tt-posts
    field usrId as char format "x(12)"
    field id as char format "x(12)"
    field postTitle as char format "x(50)"
    field postBody as char format "x(75)".



    oClient = ClientBuilder:Build():Client.

    oCreds = new Credentials('aplicattion', 'integracao', '9yFTe1CF').



    oUri = new URI('http', '191.233.25.152', 6017).
    oUri:path = '/api/millenium_eco/pedido_venda/listafaturamentos?data_atualizacao=2020-02-04-11-40-31&vitrine=84&saida_inicial=15&trans_id=73&aprovado=false&cancelada=false&data_atualizacao_inicial=2020-02-04-11-40-31&data_atualizacao_final=2020-02-04-11-40-31&lancamentos_pedido=false&saida=27&gera_xml=text&data_emissao=2020-02-04"&data_emissao_inicial=2020-02-04-11-40-31&data_emissao_final=2020-02-04-11-40-31&nota=80&pedidov=23&cod_pedidov=text&lancamentos_pedido_filial=false&filiais=text&$format=json'.
    oReq = RequestBuilder:Get(oUri)
    :UsingBasicAuthentication(oCreds)
    :Request.

    oResp = oClient:Execute(oReq).


    MESSAGE oResp :StatusCode SKIP
    oResp :StatusReason
    VIEW-AS ALERT-BOX INFO BUTTONS OK.

    /* Faz a requisicao utilizando GET */
    oReq = RequestBuilder:Get(oUri)
    :Request.
    oResp = oClient:Execute(oReq).
    /* FIM - requisicao web */

    /* trata o retorno */
    empty temp-table tt-posts.

    /* valida o tipo de retorno, se for Json processa normalmente */
    if type-of(oResp:Entity, JsonArray)
    then do:

    oJsonRespArray = cast(oResp:Entity, JsonArray).

    oJsonArray = oJsonRespArray.

    /* Mostra o total de registros retornados */
    message oJsonArray:length
    view-as alert-box.


    end.

    /* *************************** FIM *************************** */
    message "FIM"
    view-as alert-box.

    catch oError as Progress.Lang.Error :
    message
    oError:GetMessage(1) skip(2)
    oError:CallStack
    view-as alert-box.
    end catch.



    Desde já muito obrigado.
  2. af.dums

    af.dums Membro Ativo

    Teoricamente tu pode mondar um JSON e mandar como abaixo

    Código:
    oRequest = RequestBuilder:Put(httpUrl, oJson)
    :AcceptJson()
    :Request.
    
    Ai dentro do objeto "oJson" tu passa os parametros em formato de array de objetos...


    {
    "data_atualizacao": "2020-02-04-11-40-31",
    "vitrine": "84",
    "saida_inicial": "15"
    }

    Obs: digo teoricamente devido a não saber como o destino foi montado para receber os parâmetros...
    rohis curtiu isso.
  3. af.dums

    af.dums Membro Ativo

    Só corrigindo que no exemplo mandei como put, mas seria get

    RequestBuilder:get...
    rohis curtiu isso.
  4. Neivaldo

    Neivaldo Membro Participativo

    Bom dia Anderson,

    Amigo agora estou tentando testar o retorno, coloquei mensagens na parte do código onde é feito o teste não retorna nada.

    Teria alguma outra forma para testar o retorno?

    Desde já obrigado.

    Arquivos Anexados:

  5. af.dums

    af.dums Membro Ativo

    Olá
    Pelo que testei aqui...
    Ele está retornando o JsonObject não um array neste caso. Outra coisa, ele nem sempre retorna, acredito que o servidor tenha um timer para evitar "robozinhos"...

    Código:
    block-level on error undo, throw.
    
    using OpenEdge.Net.HTTP.ClientBuilder.
    using OpenEdge.Net.HTTP.Credentials.
    using OpenEdge.Net.HTTP.IHttpClient.
    using OpenEdge.Net.HTTP.IHttpRequest.
    using OpenEdge.Net.HTTP.RequestBuilder.
    using OpenEdge.Net.URI.
    using OpenEdge.Net.HTTP.IHttpResponse.
    using Progress.Json.ObjectModel.JsonObject.
    using Progress.Json.ObjectModel.JsonArray.
    
    
    
    /* *************************** Main Block *************************** */
    define variable oClient as IHttpClient no-undo.
    define variable oUri as URI no-undo.
    define variable oReq as IHttpRequest no-undo.
    define variable oResp as IHttpResponse no-undo.
    define variable oCreds as Credentials no-undo.
    define variable oJson as JsonObject no-undo.
    
    def var oJsonRespObj as JsonObject no-undo.
    
    oClient = ClientBuilder:Build():Client.
    
    oCreds = new Credentials('aplicattion', 'integracao', '9yFTe1CF').
    
    oUri = new URI('http', '191.233.25.152', 6017).
    oUri:Path = '/api/millenium_eco/pedido_venda/listafaturamentos?data_atualizacao=2020-01-01&vitrine=84&trans_id=3410&$format=json'.
    oReq = RequestBuilder:Get(oUri,oJson)
    :AcceptJson()
    :UsingBasicAuthentication(oCreds)
    :Request.
    
    oResp = oClient:Execute(oReq).
    
    DEF VAR c-caminho AS CHAR NO-UNDO.
    ASSIGN c-caminho = "X:\milleniun-neivaldo\".
    
    IF TYPE-OF(oResp:Entity, JsonObject) THEN DO:
    MESSAGE "jsonObject"
    VIEW-AS ALERT-BOX INFO BUTTONS OK.
    oJsonRespObj = CAST(oResp:Entity, JsonObject).
    
    CAST(oResp:Entity, JsonObject):WriteFile(c-caminho + 'teste-neivaldo-objeto.json', true).
    
    
    END.
    
    
  6. af.dums

    af.dums Membro Ativo

    Esse convertendo o Object do Json em Array
    Código:
    block-level on error undo, throw.
    
    using OpenEdge.Net.HTTP.ClientBuilder.
    using OpenEdge.Net.HTTP.Credentials.
    using OpenEdge.Net.HTTP.IHttpClient.
    using OpenEdge.Net.HTTP.IHttpRequest.
    using OpenEdge.Net.HTTP.RequestBuilder.
    using OpenEdge.Net.URI.
    using OpenEdge.Net.HTTP.IHttpResponse.
    using Progress.Json.ObjectModel.JsonObject.
    using Progress.Json.ObjectModel.JsonArray.
    
    
    
    /* ***************************  Main Block  *************************** */
    define variable oClient as IHttpClient no-undo.
    define variable oUri as URI no-undo.
    define variable oReq as IHttpRequest no-undo.
    define variable oResp as IHttpResponse no-undo.
    define variable oCreds as Credentials no-undo.
    define variable oJson as JsonObject no-undo.
    define variable oJsonArray as JsonArray no-undo.
    define variable oJsonObj as JsonObject no-undo.
    
    def var oJsonRespObj   as JsonObject         no-undo.       
    
    DEF VAR i AS INTEGER NO-UNDO.
    
    oClient = ClientBuilder:Build():Client.
    
    
    
    oCreds = new Credentials('aplicattion', 'integracao', '9yFTe1CF').
    
    oUri = new URI('http', '191.233.25.152', 6017).
    oUri:Path = '/api/millenium_eco/pedido_venda/listafaturamentos?data_atualizacao=2020-01-01&vitrine=84&trans_id=3410&$format=json'.
         oReq = RequestBuilder:Get(oUri,oJson)
                :AcceptJson()
                :UsingBasicAuthentication(oCreds)
                :Request.
    
    oResp = oClient:Execute(oReq).
    
    DEF VAR c-caminho AS CHAR NO-UNDO.
    ASSIGN c-caminho = "X:\milleniun-neivaldo\".
    
    IF TYPE-OF(oResp:Entity, JsonObject) THEN DO:
        MESSAGE "jsonObject"
            VIEW-AS ALERT-BOX INFO BUTTONS OK.
        oJsonRespObj = CAST(oResp:Entity, JsonObject).
    
        CAST(oResp:Entity, JsonObject):WriteFile(c-caminho + 'teste-neivaldo-objeto.json', true).
    
        oJsonArray = oJsonRespObj:getJsonArray('value') NO-ERROR.
       
        MESSAGE 'achou: ' oJsonArray <> ?
            VIEW-AS ALERT-BOX INFO BUTTONS OK.
    
        IF oJsonArray = ? OR oJsonArray:LENGTH <= 0 THEN DO:
            MESSAGE "vaziooo"
                VIEW-AS ALERT-BOX INFO BUTTONS OK.
        END.
        ELSE DO:
    
            MESSAGE "Registros: " oJsonArray:LENGTH
            VIEW-AS ALERT-BOX INFO BUTTONS OK.
    
            /* Converte de Json para Registros na temp-table */
            Loop1:
            do i=1 to oJsonArray:length on error undo, next:
                oJsonObj = oJsonArray:GetJsonObject(i).
       
                MESSAGE "saida: " string(oJsonObj:GetInt64("saida")) SKIP
                        "tipo_operacao: " oJsonObj:GetCharacter("tipo_operacao") SKIP
                        "romaneio: " oJsonObj:GetCharacter("romaneio") SKIP
                        "nf: " oJsonObj:GetCharacter("nf")
                    VIEW-AS ALERT-BOX INFO BUTTONS OK.
               
            end.
        END.
    
    
    END.
    
    
    rohis curtiu isso.

Compartilhe esta Página