Grails - 从我的 POST 请求 HTTP 中获取 return
Grails - Get return from my POST request HTTP
我有一个 POST 类型的 REST 调用的 grails 代码,我在其中传递了登录参数,它是为了接收令牌和访问路由,这是正确的,都是通过 Postman 获得这些参数的是的,毕竟根据代码,错误处理并没有落空。
我从 Posman 那里得到的答案是这样的:
{
"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}"
,returns 我的空 JSon 参数。
谁能指出我做错了什么?如果有其他方法可以在 grails 中进行此调用,还是我得到的答案不正确?
更新
我可以通过 Postman 安静地执行 post,我想这可能是因为我进入了 Headers 参数 Content-Type = 'application/json'
,有谁知道如何在 grails 中使用 HTTPBuilder
执行此操作?
更新 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]
}
}
更新调用,使其看起来像:
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}
我有一个 POST 类型的 REST 调用的 grails 代码,我在其中传递了登录参数,它是为了接收令牌和访问路由,这是正确的,都是通过 Postman 获得这些参数的是的,毕竟根据代码,错误处理并没有落空。
我从 Posman 那里得到的答案是这样的:
{
"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}"
,returns 我的空 JSon 参数。
谁能指出我做错了什么?如果有其他方法可以在 grails 中进行此调用,还是我得到的答案不正确?
更新
我可以通过 Postman 安静地执行 post,我想这可能是因为我进入了 Headers 参数 Content-Type = 'application/json'
,有谁知道如何在 grails 中使用 HTTPBuilder
执行此操作?
更新 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]
}
}
更新调用,使其看起来像:
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}