I have a grails code for a POST type REST call where I pass the login parameters and it was to receive the token and an access route, it is correct, both by Postman that I get these parameters right, and by the code also after all, it does not fall no catch for error handling.
The answer I get from Posman goes something like this:
{
"access_token": "and ... 2",
"instance_url": "http: \ / \ / m ... \ / .. c"
}
This is the one excerpt from my grails code:
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}"
}
But my debug line log.debug "** access_token: $ {json.access_token}, instance_domain: $ {json.instance_url}"
, returns me the empty JSon parameter.
Can anyone point out to me what I'm doing wrong? If there is another way to do this call in grails, or am I getting the answer incorrectly?
UPDATE
I can do the post quietly by Postman, I think maybe it's because I step in the Headers parameter Content-Type = 'application/json'
, does anyone know how to do this in grails with HTTPBuilder
?
UPDATE 2
My code class.groovy completed
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]
}
}
Update the call so it looks like:
http.post (path: 'ApplyLogin', body: postBody, contentType:JSON, requestContentType: URLENC) {
UPDATE:
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 }
}
prints out:
{access_token=xxx-yyy-zzz....., instance_url=some_url}