HTTPBuilder set request contenttype

Marco picture Marco · Feb 25, 2013 · Viewed 13.9k times · Source

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
    }
}

Answer

Marco picture Marco · Feb 26, 2013

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
}

}