Grails - 从我的POST请求HTTP返回

时间:2018-04-27 15:17:19

标签: rest http grails groovy httpbuilder

我有一个用于POST类型REST调用的grails代码,其中我传递了登录参数,它是接收令牌和访问路由,它是正确的,由Postman我得到这些参数,并且通过代码毕竟,它并没有陷入错误处理。

我从波斯曼得到的答案是这样的:

{
"access_token": "and ... 2",
"instance_url": "http: \ / \ / m ... \ / .. c"
}

这是我的grails代码的摘录:

    def http = new HTTPBuilder (sf_login_domain)
    def postBody = [
        grant_type: 'password',
        client_id: consumer_key,
        client_secret: consumer_secret,
        username: auth_username,
        password: auth_password
    ]
    try {
        http.post (path: 'ApplyLogin', body: postBody, requestContentType: URLENC) {
          resp, json ->
            log.debug "** access_token: $ {json.access_token}, instance_domain: $ {json.instance_url}"
            access_token = json.access_token
            instance_domain = json.instance_url + "/"
        }
        returnLogin = ['access_token': access_token, 'instance_domain': instance_domain]
    }
    catch (Exception e) {
        log.error "** Error code: $ {e}"
        log.error "** Post form: $ {postBody}"
    }

但我的调试行log.debug "** access_token: $ {json.access_token}, instance_domain: $ {json.instance_url}",返回空的JSon参数。

任何人都可以向我指出我做错了什么吗?如果还有其他方法可以使用grails进行此调用,或者我得到的答案是错误的吗?

更新

我可以通过Postman悄悄地发帖子,我想也许是因为我进入了Headers参数Content-Type = 'application/json',是否有人知道如何使用HTTPBuilder在grails中执行此操作?

enter image description here

更新2

我的代码class.groovy已完成

    package crm.emp

        import groovyx.net.http.HTTPBuilder
        import groovyx.net.http.HttpResponseException
        import static groovyx.net.http.ContentType.URLENC
        import static groovyx.net.http.Method.POST
        import static groovyx.net.http.Method.GET
        import static groovyx.net.http.Method.PATCH
        import static groovyx.net.http.ContentType.JSON

        class CrmService {

            def grailsApplication

    static transactional = true

    def login() {
        log.info "* Login"

        def sf_login_domain = grailsApplication.config.crm.sf_login_domain
        def consumer_key = grailsApplication.config.crm.consumer_key
        def consumer_secret = grailsApplication.config.crm.consumer_secret
        def auth_username = grailsApplication.config.crm.auth_username
        def auth_password = grailsApplication.config.crm.auth_password
        def retornoLogin
        def access_token
        def instance_domain

        //Request Access_token and instance domain for work
        def http = new HTTPBuilder(sf_login_domain)
        def postBody = [
            grant_type: 'password',
            client_id: consumer_key,
            client_secret: consumer_secret,
            username: auth_username,
            password: auth_password
        ]
        try {
            http.post( path : 'EfetuarLogin', contentType :JSON, body : postBody) {
              resp, json ->
                log.debug "**  json: ${json.EfetuarLogin}"
                log.debug "**  access_token: ${json.EfetuarLogin.access_token}, instance_domain: ${json.EfetuarLogin.instance_url}"
                access_token = json.EfetuarLogin.access_token
                instance_domain = json.EfetuarLogin.instance_url
            }
            coss.Parametro.executeUpdate("update Parametro p set p.valor='$access_token' where p.chave='ACCESS_TOKEN_SALES_FORCE'")
            coss.Parametro.executeUpdate("update Parametro p set p.valor='$instance_domain' where p.chave='INSTANCE_DOMAIN_SALES_FORCE'")
            retornoLogin = ['access_token':access_token, 'instance_domain':instance_domain]
        }
        catch(Exception e){
            log.error "** Error code: ${e}"
            log.error "** Post form: ${postBody}"
        }
        return retornoLogin
    }

    def verificaAcessoCrm() {
        log.info "* VerificaAcessoCrm - teste 29"

        def access_token = coss.Parametro.findByChave('ACCESS_TOKEN_SALES_FORCE')?.valor
        def instance_domain = coss.Parametro.findByChave('INSTANCE_DOMAIN_SALES_FORCE')?.valor

        def retornoLogin

        if(access_token && instance_domain) {

          def http = new HTTPBuilder(instance_domain)
          def postBody = [
            token_type:'Bearer',
            access_token:access_token
          ]
          try {
              http.post( path : 'VerificarAcesso', contentType:JSON, body : postBody) {
                resp, json ->
                access_token = json.VerificarAcesso.access_token
                instance_domain = json.VerificarAcesso.instance_domain
              }
              retornoLogin = ['access_token':access_token, 'instance_domain':instance_domain]
          }
          catch(Exception e){
              log.error "** Error code: ${e}"
              log.error "** Post form: ${postBody}"
              retornoLogin = login()
          }
        }else{
          retornoLogin = login()
        }

        log.debug "** RetornoLogin: ${retornoLogin}"

        return retornoLogin
    }

    def atualizaPedidoCrm(numeroCRM, dataFim, codigo, nfe, series, danfeEmitido, boletoEmitido, formaDeEnvio) {
        log.info "* AtualizaPedidoCrm"
        log.debug "**  DataFim: ${dataFim}, codigo:${codigo}, nfe:${nfe}, danfeEmitido:${danfeEmitido}, boletoEmitido:${boletoEmitido}, formaDeEnvio:${formaDeEnvio}"

        def urlOpportunity

        def verificaAcessoCrm = verificaAcessoCrm()

        def access_token = verificaAcessoCrm.access_token
        def instance_domain = verificaAcessoCrm.instance_domain

        if(access_token && instance_domain && dataFim) {
            // urlOpportunity = buscaPedidoCrm(numeroCRM, access_token, instance_domain)
            // busca o pedido com os campos da nota
            urlOpportunity = buscaPedidoCrmENfe(numeroCRM, access_token, instance_domain)
            log.info "** UrlOpportunity: ${urlOpportunity}"

            if(urlOpportunity) {

                if (urlOpportunity?.nfe1 == nfe.toString()+'-'+series.toString() ||
                    urlOpportunity?.nfe2 == nfe.toString()+'-'+series.toString() ||
                    urlOpportunity?.nfe3 == nfe.toString()+'-'+series.toString()){
                    return 0
                }
                def postBody = []

                if(urlOpportunity?.nfe1 == null || urlOpportunity?.nfe1 == ''){
                  postBody = [
                    token_type:'Bearer',
                    access_token:access_token,
                    Numero_do_pedido__c:numeroCRM,
                    Data_saida_expedicao__c:dataFim.format('yyyy-MM-dd'),
                    N_Remessa__c:codigo.toString(),
                    Foi_expedido__c: true,
                    N_mero_da_Nota_Fiscal__c:nfe.toString()+'-'+series.toString(),
                    Nota_fiscal_emitida__c: danfeEmitido,
                    Boleto_enviado__c: boletoEmitido,
                    meio_envio_COSS__c:formaDeEnvio.toString()
                  ]
                }
                else if(urlOpportunity?.nfe2 == null || urlOpportunity?.nfe2 == ''){
                  postBody = [
                    token_type:'Bearer',
                    access_token:access_token,
                    Numero_do_pedido__c:numeroCRM,
                    N_mero_da_Nota_Fiscal_2__c:nfe.toString()+'-'+series.toString(),
                    N_de_Remessa_2__c:codigo.toString(),
                    Data_Sa_da_Expedi_o_Embarque_2__c:dataFim.format('yyyy-MM-dd'),
                    Meio_de_Envio_COSS_2__c:formaDeEnvio.toString()
                  ]
                }
                else if(urlOpportunity?.nfe3 == null || urlOpportunity?.nfe3 == ''){
                  postBody = [
                    token_type:'Bearer',
                    access_token:access_token,
                    Numero_do_pedido__c:numeroCRM,
                    N_mero_da_Nota_Fiscal_3__c:nfe.toString()+'-'+series.toString(),
                    N_de_Remessa_3__c:codigo.toString(),
                    Data_Sa_da_Expedi_o_Embarque_3__c:dataFim.format('yyyy-MM-dd'),
                    Meio_de_Envio_COSS_3__c:formaDeEnvio.toString()
                  ]
                }

                def http = new HTTPBuilder(instance_domain)
                try {
                    http.post( path : "AtualizarPedido/"+urlOpportunity.url, contentType:JSON, body : postBody) {
                      resp, json ->
                        log.info "** Status: $resp.status"
                    }
                }
                catch(Exception e){
                    log.error "** Error code: ${e}"
                    log.error "** Post form: ${postBody}"
                }
            }
        }
    }

    def buscaDadosCrm(numeroCRM) {
        log.info "* BuscaDadosCrm - Consultar Pedido"
        log.debug "**  numeroCRM: ${numeroCRM}"

        def verificaAcessoCrm = verificaAcessoCrm()

        def access_token = verificaAcessoCrm.access_token
        def instance_domain = verificaAcessoCrm.instance_domain

        def formaDeEnvio
        def tipoVenda
        def pedidoRelacionadoCrm

        def http = new HTTPBuilder(instance_domain)
        def postBody = [
          token_type:'Bearer',
          access_token:access_token,
          Numero_do_pedido__c:numeroCRM
        ]
        try {
            http.post( path : 'ConsultarPedido', contentType:JSON, body : postBody) {
              resp, json ->
                formaDeEnvio = json.ConsultarPedido.meio_envio_COSS__c
                tipoVenda = json.ConsultarPedido.Tipo_de_Pedido__c
                pedidoRelacionadoCrm = json.ConsultarPedido.Numero_do_pedido_na_OBS__c
            }
            log.debug "** Forma de envio: $formaDeEnvio | Tipo Venda: $tipoVenda | Pedido Relacionado: $pedidoRelacionadoCrm"
        }
        catch(Exception e){
            log.error "** Error code: ${e}"
            log.error "** Post form: ${postBody}"
        }

        return [formadeEnvio:formaDeEnvio, tipoVenda:tipoVenda, pedidoRelacionadoCrm:pedidoRelacionadoCrm]
    }

    /*def buscaPedidoCrm(numeroCRM, access_token, instance_domain) {
        log.info '*buscaPedidoCrm'
        log.debug "* numeroCRM: ${numeroCRM}"

        def url

        def http = new HTTPBuilder(instance_domain)
        http.request(GET,JSON) { req ->
          uri.path = 'consultarpedido/'+numeroCRM
          headers['Authorization'] = "Bearer $access_token"

          response.success = { resp, json  ->
            assert resp.status == 200
            url = json.attributes.url
          }

          response.failure = { resp, json ->
            log.debug "$resp.status"
            //log.debug "$json?.errorCode"
            //log.debug "$json?.message"
          }
        }
        log.debug "*url: $url"
        return url
    }*/

    // metodo adiconada pois a Sin (Brill e Luciana) querem garvar mais de uma nota
    def buscaPedidoCrmENfe(numeroCRM, access_token, instance_domain){
        log.info "* BuscaPedidoCrmENfe - Consultar Notas"
        log.debug "** NumeroCRM: ${numeroCRM}"

        def url
        def nfe_1
        def nfe_2
        def nfe_3

        def http = new HTTPBuilder(instance_domain)
        def postBody = [
          token_type:'Bearer',
          access_token:access_token,
          Numero_do_pedido__c:numeroCRM
        ]
        try {
            http.post( path : 'ConsultarNotas', contentType:JSON, body : postBody) {
              resp, json ->
                url = json.ConsultarNotas.attributes.url
                nfe_1 = json.ConsultarNotas.N_mero_da_Nota_Fiscal__c
                nfe_2 = json.ConsultarNotas.N_mero_da_Nota_Fiscal_2__c
                nfe_3 = json.ConsultarNotas.N_mero_da_Nota_Fiscal_3__c
            }
            log.debug "** Url: $url | Nfe1: $nfe_1 | Nfe2: $nfe_2 | NFfe3: $nfe_3 "
        }
        catch(Exception e){
            log.error "** Error code: ${e}"
            log.error "** Post form: ${postBody}"
        }
        return [url:url, nfe1:nfe_1, nfe2:nfe_2, nfe3:nfe_3]
    }
}

1 个答案:

答案 0 :(得分:3)

更新通话,如下所示:

http.post (path: 'ApplyLogin', body: postBody, contentType:JSON, requestContentType: URLENC) {

更新:

HTTPBuilder hb = new HTTPBuilder( url )
hb.request( POST, JSON ){ req ->
  uri.path = 'EfetuarLogin'
  body = [ "grant_type": "password",
           "client_id": "xxx",
           "client_secret": "yyy",
           "username": "zzz",
           "password": "*****" ]

  response.success = { resp, json -> println json }
}

打印出来:

{access_token=xxx-yyy-zzz....., instance_url=some_url}