3

I am using the following code to execute a HTTP POST towards an external system. The problem is that the external system always gets a 'null' content type when using the code below. Is there a way to set the contenttype when using HTTPBuilder.

I tried other tools that execute the same request but then the remote system gets a good contentType ('application/json').

    def execute(String baseUrl, String path, Map requestHeaders=[:], Map query=[:], method = Method.POST) {
    try {
        def http = new HTTPBuilder(baseUrl)
        def result = null

        // perform a ${method} request, expecting TEXT response
        http.request(method, ContentType.JSON) {
            uri.path = path
            uri.query = query

            // add possible headers
            requestHeaders.each { key, value ->
                headers."${key}" = "${value}"
            }

            // response handler for a success response code
            response.success = { resp, reader ->
                result = reader.getText()
            }
        }
        return result
    } catch (groovyx.net.http.HttpResponseException ex) {
        ex.printStackTrace()
        return null
    } catch (java.net.ConnectException ex) {
        ex.printStackTrace()
        return null
    }
}
Marco
  • 15,101
  • 33
  • 107
  • 174

2 Answers2

1

Adding a specific header to the request seems to solve my problem.

def execute(String baseUrl, String path, Map requestHeaders=[:], Map query=[:], method = Method.POST) {
try {
    def http = new HTTPBuilder(baseUrl)
    def result = null

    // perform a ${method} request, expecting TEXT response
    http.request(method, ContentType.JSON) {
        uri.path = path
        uri.query = query
        headers.'Content-Type' = 'application/json'

        // add possible headers
        requestHeaders.each { key, value ->
            headers."${key}" = "${value}"
        }

        // response handler for a success response code
        response.success = { resp, reader ->
            result = reader.getText()
        }
    }
    return result
} catch (groovyx.net.http.HttpResponseException ex) {
    ex.printStackTrace()
    return null
} catch (java.net.ConnectException ex) {
    ex.printStackTrace()
    return null
}

}

Marco
  • 15,101
  • 33
  • 107
  • 174
0

Try setting the requestContentType in the body of your request block...

http.request(method, ContentType.JSON) {
            uri.path = path
            uri.query = query
            requestContentType = groovyx.net.http.ContentType.URLENC

     .......
}
Gregg
  • 34,973
  • 19
  • 109
  • 214