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 } } 
2
  • It seems you're doing it right. Is there a chance of your map parameter requestHeaders could be resetting Content-Type key? Commented Feb 25, 2013 at 12:52
  • Nope, i removed the lines but still the remote system gets a 'null' as contentType Commented Feb 25, 2013 at 14:13

2 Answers 2

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 } 

}

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

I tried your suggestion but still giving me 'null' on the receiver side.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.