0

We're trying to use Groovy's HTTPBuilder's request method to send a POST request with a content type of application/x-www-form-urlencoded, and parse the response from the server, which has a content type of application/json.

The library ignores the Content-Type header in the response, and wants to parse it as application/x-www-form-urlencoded.

Our code looks like this:

import static groovyx.net.http.ContentType.URLENC
import static groovyx.net.http.Method.POST
import groovyx.net.http.HTTPBuilder


def http = new HTTPBuilder('https://example.com')
def result = http.request(POST, URLENC) {
    uri.path = "/some/path"
    body = [
        someProperty: "someValue"
    ]
}

I can see from the wire logs that the request has a Content-Type: application/x-www-form-urlencoded header, and the response has a Content-Type: application/json header - and the response is well-formed JSON, but the debug log for HTTPBuilder emits this line:

DEBUG http.HTTPBuilder  - Parsing response as: application/x-www-form-urlencoded

And indeed, parses the response as though it was x-www-urlencoded.

I've looked through HTTPBuilder's source and it seems as though it wants to ignore the content type of the response if the content type of the request is anything other than */*.

Based on this, we've managed to make it work as desired by configuring the HTTPBuilder instance such that:

http.parser.'application/x-www-form-urlencoded' = http.parser.'application/json'

...but changing the parser for x-www-form-urlencoded seems like taking a crowbar to the library. Is there an idiomatic way to tell HTTPBuilder to use one content type for the request and use the Content-Type header of the response to parse the result?

AML
  • 312
  • 3
  • 10

1 Answers1

1

Answering my own question...

The second parameter to http.request tells it to explicitly use that content type for the response, we can get the results we intended like this:

def http = new HTTPBuilder('https://example.com')
def result = http.request(POST) {
    requestContentType = URLENC
    uri.path = "/some/path"
    body = [
        someProperty: "someValue"
    ]
}
AML
  • 312
  • 3
  • 10