[Static type checking] variable [requestContentType] is undeclared

Tamil June 23, 2020

Hi,

I am trying to write a script in Jira Workflow postfunction which sends POST to external server.

Below is my script to send POST request to url(http://test:8000). The below script gives error as

[static type checking] the variable [requestContentType] is undeclared

[static type checking] the variable [response] is undeclared

[static type checking] the variable [resp.status] is undeclared

I am new to groovy script. Could you please help me in understanding why the error occurs and correct way to send POST request to URL?

 

import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.ContentType.*
import groovyx.net.http.ContentType
import static groovyx.net.http.Method.*
import groovy.json.JsonSlurper
import net.sf.json.groovy.JsonSlurper

def http = new HTTPBuilder('http://test:8000/process')
http.request(GET) {
requestContentType = ContentType.JSON
//body = [region: 'USERNAME', password: 'PASSWORD']

response.success = { resp, JSON ->

return JSON

}

response.failure = { resp ->
return "Request failed with status ${resp.status}"

}
}

 

Regards,

Tamil

1 answer

0 votes
Slava Dobromyslov April 6, 2023

Yes, it's the nature of Groovy.

It seems to me you show us only a part of the code. This error occurs when you mark a class as compiled static. You can't do this with @CompileStatic annotation because HTTPBuilder uses a dynamic delegate for configuration.

Remove the @CompileStatic annotation, and everything will work. Here is my example:

import groovyx.net.http.ContentType
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.HttpResponseDecorator
import groovyx.net.http.Method

// Do not mark it as @CompileStatic
class SomeService {
static void sendNotification() {
final http = new HTTPBuilder('https://example.com/notify')
http.request(Method.POST, ContentType.JSON) {
headers.put('authorization', 'Bearer MY_TOKEN')
body = [
text: text,
]

response.success = { HttpResponseDecorator resp, Object json ->
assert resp.status == 200
return json
}

response.failure = { HttpResponseDecorator resp ->
throw new RuntimeException(
"Can't send notification: " +
"${resp.getStatus()} ${resp.getStatusLine().getReasonPhrase()}"
)
}
}
}
}

 

Also, see more info in the RequestConfigDelegate

 

Suggest an answer

Log in or Sign up to answer